Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribing to MvxMessage from Android Client

Using Xamarin and MvvmCross, where in an Android Client View do I subscribe to messages from the Core project, I tried this code which doesn't get executed:

 public HomeView(IMvxMessenger messenger)
 {
     _messenger = messenger;

     // Subscribe to inter-app message "ApplicationError_Message"
     _messageToken = messenger.SubscribeOnMainThread<ApplicationError_Message>(Display_Error);
 }
like image 655
samneric Avatar asked Jul 12 '26 10:07

samneric


1 Answers

I couldn't really follow your example code - it didn't really explain:

  • how you were creating your HomeView
  • how it was getting its messenger instance passed to it.
  • what was generating the ApplicationError_Message messages
  • how you were understanding whether or not the message was or wasn't arriving

As a quick test I modified the Android HomeView in the InternetMinute sample - https://github.com/slodge/MvvmCross-Tutorials/tree/master/InternetMinute

using Android.App;
using Android.OS;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Droid.Views;
using Cirrious.MvvmCross.Plugins.Messenger;
using InternetMinute.Core;

namespace InternetMinute.Droid.Views
{
    [Activity(Label = "Internet time is ticking")]
    public class HomeView : MvxActivity
    {
        private MvxSubscriptionToken _token;

        private IMvxMessenger _messenger;
        protected IMvxMessenger Messenger
        {
            get 
            { 
                _messenger = _messenger ?? Mvx.Resolve<IMvxMessenger>();
                return _messenger;
            }
        }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.HomeView);
        }

        protected override void OnResume()
        {
            base.OnResume();
            _token = Messenger.SubscribeOnMainThread<TickMessage>(OnTick);
        }

        protected override void OnPause()
        {
            Messenger.Unsubscribe<TickMessage>(_token);
            _token = null;
            base.OnPause();
        }

        private int _i = 0;
        private void OnTick(TickMessage obj)
        {
            Mvx.Trace("Tick received {0}", ++_i);
        }
    }
}

That seemed to work fine - I got the trace I was expecting.

Perhaps your SubscribeOnMainThread isn't subscribing for the correct message type - what type is the compiler inferring?

like image 142
Stuart Avatar answered Jul 15 '26 00:07

Stuart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!