samneric
samneric

Reputation: 3218

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);
 }

Upvotes: 3

Views: 2242

Answers (1)

Stuart
Stuart

Reputation: 66882

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?

Upvotes: 7

Related Questions