Switching to ShouldAlwaysRaiseInpcOnUserInterfaceThread(false) MVVMCross - xamarin

We are in the process of moving from MVVMCross 4.1 to 4.4. One of the main things for us to consider is the MvxTaskBasedBindingContext that was introduced in 4.2.
In the MVVMCross 4.2 docs it says
To take full advantage of the MvxTaskBasedBindingContext, you should
also call ShouldAlwaysRaiseInpcOnUserInterfaceThread(false); in the
ViewModel constructor.
MvxTaskBasedBindingContext sounds like a good thing and therefore we want to take "full advantage" of it. However unsurprisingly, no longer always raising INotifyPropertyChanged on the UI Thread gives us plenty of Thread Marshalling errors
"Application called an interface that was marshalled for a different thread"
Is there a suggested approach to moving to the ShouldAlwaysRaiseInpcOnUserInterfaceThread(false) model and is only worth it in certain scenarios?

If you take a look at the implementation of MvxNotifyPropertyChanged, you'll see that RaisePropertyChanged by default marshals PropertyChanged events to the UI thread.
So if you are performing Unit Tests on the PropertyChanged event they'll probably break because there is no Dispatcher. Setting ShouldAlwaysRaiseInpcOnUserInterfaceThread(false) will prevent this situation and the raise will be done directly on the thread you are in that moment.
This is also handy when you are subscribed to PropertyChanged in another thread on purpose.
If you want you can set it to false and make a method on your base viewmodel class to do:
this.InvokeOnMainThread(() => this.RaisePropertyChanged(propertyName));
So you always use your RaisePropertyChangedOnMainThread (let's name it like this) and no thread marshalling errors occur.
Source: http://www.damirscorner.com/blog/posts/20140324-HandlingPropertyChangedEventInMvvmCrossViewModelUnitTests.html
HIH

Related

Use PropertyChanged or WeakSubscribe?

What is the best way to track a property change?
I have the following concerns why I can't make a decision.
- PropertyChanged can prevent garbage collection from collecting a ViewModel that uses its own PropertyChanged event?
- Could WeakSubscribe be gone at any moment in time when using to track ViewModels own property changes?
Did anyone test this or just know the answer ?
In general, you won't hit problems if you use PropertyChanged strong subscriptions.... However, there are some cases where this can lead to "leaks" - e.g. if you subscribe on a sub-object which has a longer lifetime than a "normal" ViewModel (e.g. a singleton service).
To be safe, though, you can use WeakSubscribe - as long as you store a reference to the returned token from the WeakSubscribe call in a member field in your view, then this will ensure that the subscription remains active for at least as long as your View is in memory.
Regardless of strong or weak, one additional thing to aim for ... is to try to release the event subscription (either strong or weak) as early as you can. This will help prevent event callbacks being fired after the View has disappeared.

Should I prefer NSNotificactionCenter or .NET events when using Monotouch?

When developing in Monotouch, is it "better" to us real .NET events or NSNotificationCenter?
Simple example: I have a UIViewController. It offers an event "CallbackWhenDisappeared". This event is triggred in ViewDidDisappear. Who ever is interested can register to the event.
I could as well post a "MyFancyControllerHasDisappeared" on the NSNotificationCenter and let interested objects subscribe there.
Which version is to be preferred?
The disadvantage with the .NET events I see: the disappearing controller might hold a reference to the subscribing controller (or the other way round?) and might not be garbage collected.
I also like the loose coupling when using NSNotificationCenter compared to the events where the classes really have to know each other.
Is there a wrong or a right way of doing it?
I actually prefer to use TinyMessenger. Unlike NSNotifications it handles the asynchronicity of the calls for you as part of the framework.
Managed objects also allow for better debuggability especially considering that these are usually cross container calls I find this to be very very useful.
var messageHub = new TinyMessengerHub();
// Publishing a message is as simple as calling the "Publish" method.
messageHub.Publish(new MyMessage());
// We can also publish asyncronously if necessary
messageHub.PublishAsync(new MyMessage());
// And we can get a callback when publishing is completed
messageHub.PublishAsync(new MyMessage(), MyCallback);
// MyCallback is executed on completion
https://github.com/grumpydev/TinyMessenger
There is no really right or wrong, but in my opinion it looks so:
NotificationCenter - You don't know which Objects are interested on the "Events", you send it out and any object can receive it
.Net Events - If there is a direct connection between two objects use this, for example like an UIViewController shows an other UIViewcontroller as Modal. The ModalUIViewcontroller fires an event, if it will hide and the UIViewController is Suscribed to it

Synchronizing Event Calls from Threads to Event Handlers on Windows Forms

I have an object that is updated from a polling loop on a thread. This object fires particular events when data changes, etc.
I'm trying to use this object in conjunction with a windows form, where I create event handlers on the form to update the UI. Of course, this causes cross-thread operation exceptions if I try to manipulate the UI directly in these handlers.
I can get it to work by going through the standard procedure of checking InvokeRequired, using a delegate, blah blah blah. But I want to publish this object as a library, and I don't want end-users to have to worry about all that.
I want my object to somehow take care of synchronizing those event callbacks with the form so that end-users can manipulate the UI elements in those handlers worry-free.
Is there a way to do this??
If your object is always related to a single form, there is a simple trick indeed. The important fact here is, that you instanciate your object from the thread you like to affect the form later.
The trick is to instanciate a simple Control (new Control()) in your object in the constructor. When you perform logic on your form, use the Invoke/BeginInvoke methods on this simple control, to dispatch the action to the correct calling thread. So you have the dispatching logic directly in your object and there is no need for other users of your object to take care about this.

When to use events?

At work, we have a huge framework and use events to send data from one part of it to another. I recently started a personal project and I often think to use events to control the interactions of my objects.
For example, I have a Mixer class that play sound effects and I initially thought I should receive events to play a sound effect. Then I decided to only make my class static and call
Mixer.playSfx(SoundEffect)
in my classes. I have a ton of examples like this one where I initially think of an implementation with events and then change my mind, saying to myself it is too complex for nothing.
So when should I use events in a project? In which occasions events have a serious advantage over others techniques?
You generally use events to notify subscribers about some action or state change that occurred on the object. By using an event, you let different subscribers react differently, and by decoupling the subscriber (and its logic) from the event generator, the object becomes reusable.
In your Mixer example, I'd have events signal the start and end of playing of the sound effect. If I were to use this in a desktop application, I could use those events to enable/disable controls in the UI.
The difference between Calling a subroutine and raising events has to do with: Specification, Election, Cardinality and ultimately, which side, the initiator or the receiver has Control.
With Calls, the initiator elects to call the receiving routine, and the initiator specifies the receiver. And this leads to many-to-one cardinality, as many callers may elect to call the same subroutine.
With Events on the other hand, the initiator raises an event that will be received by those routines that have elected to receive that event. The receiver specifies what events it will receive from what initiators. This then leads to one-to-many cardinality as one event source can have many receivers.
So the decision as to Calls or Events, mostly has to do with whether the initiator determines the receiver is or the receiver determines the initiator.
Its a tradeoff between simplicity and re-usability. Lets take an metaphor of "Sending the email" process:
If you know the recipients and they are finite in number that you can always determine, its as simple as putting them in "To" list and hitting the send button. Its simple as thats what we use most of the time. This is calling the function directly.
However, in case of mailing list, you don't know in advance that how many users are going to subscribe to your email. In that case, you create a mailing list program where the users can subscribe to and the email goes automatically to all the subscribed users. This is event modeling.
Now, even though, in both above option, emails are sent to users, you are a better judge of when to send email directly and when to use the mailing list program. Apply the same judgement, hope that you would get your answer :)
Cheers,
Ajit.
I have been working with a huge code base at my previous work place and have seen, that using events can increase the complexity quite a lot and often unnecessarily.
I had often to reverse engineer existing code in order to fix it or to extend it.
In both cases, it is a lot easier to understand what is going on, when you can simply read a list of function calls instead of just seeing the raise of an event.
The event forces you to look for usages in order to fully understand what is happening. Not a problem with modern IDEs, but if you then encounter many functions, which also raise events, it quickly becomes complex. I had encountered cases, where it mattered in what order functions did subscribe to an event, even though most languages don't even gurantee a calling order...
There are cases when it is a really good idea to use events. But before you start eventing, consider the alternative. It is probably easier to read and mantain.
A Classic example for the use of events is a UI framework, which provides elements like buttons etc.
You want the function "ButtonPressed()" of the framework to call some of your functions, so that you can react to the user action.
The alternative to an event that you can subscribe to, would for example be a public bool "buttonPressed", which the UI framework exposes
and which you can regurlary check for beeing true or false. This is of course very ineffecient, when there are hundreds of UI elements.

Cocoa Controllers - best practice for notifying on completion, for disposal?

I have an ObjC controller object.
After alloc/init of the object, I get it to do a job asynchronously:
[myObject doSomeThingsOverTime];
The method sets things in motion, and then returns immediately.
Question: what is the best way to be notified of the result in the future, so that I can release myObject and react to the work having been completed? Should I observe/post notifications? Or supply the object with a method to callback? Or other?
I'm personally a fan of the notification center route. It allows for more than one observer (may or may not be relevant to you).
The delegate route is also valid, and is used quite frequently in the frameworks.
I think it comes down to personal preference. If it's your own code, you should go for what's most readable and simple for your particular situation. I don't think one is more or less valid than the other.
Have you looked at the NSOperation and NSOperationQueue classes? You can observe the isFinished of an NSOperation object so you will get notified when it is completed.

Resources