Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MvvmCross communication between ViewModels

I am new to MvvmCross and Xamarin. I have been looking into this for some time now and I am trying to find what is the best way to send some data from ViewModel B to ViewModel A. Meaning that ViewModel A is responsible for showing ViewModel B. It's fairly straight forward on how to send data to a ViewModel when launching it, however there is no clearly defined tutorial that I have come across that is showcasing how to send the data back to the starting ViewModel on finishing.

I have come across Event Aggregators like MvvmCross.Messenger that seems to be an ideal candidate. However for an Android project I am not sure if that is a good choice due to Android Activity life cycle methods.

Any help on this would be very well appreciated. Thank you.

like image 718
ahmad Avatar asked Mar 16 '23 00:03

ahmad


2 Answers

The Messenger is the right way to do it, it has been covered in another stack overflow question. There is even a sample code you can toy with.

The gist is that both ViewModel receive a (possibly singleton) Messenger, and when ViewModelB wants to let ViewModelA it needs to reload its data, ViewModelB sends a message through the messenger. Internally Messenger uses a WeakReference to ensure garbage collection can still go on (check this post for more information)

like image 102
Julien Lebot Avatar answered Mar 29 '23 01:03

Julien Lebot


It sounds like what you want to do is to show a VM for a particular result to be returned to the "parent" VM. This is baked into Android with StartActivityForResult, but needs some hacking to implement with MvvmCross.

Greg Shackles wrote a tutorial on how this can be accomplished. Further discussion here. It's a better fit for the Android activity flow than using the messenger, if I understand your usecase correctly.

like image 28
tempy Avatar answered Mar 29 '23 01:03

tempy