从Android客户端订阅MvxMessage

时间:2013-05-22 15:54:57

标签: android xamarin mvvmcross

使用Xamarin和MvvmCross,我在Android客户端视图中订阅了来自Core项目的消息,我尝试了这个无法执行的代码:

 public HomeView(IMvxMessenger messenger)
 {
     _messenger = messenger;

     // Subscribe to inter-app message "ApplicationError_Message"
     _messageToken = messenger.SubscribeOnMainThread<ApplicationError_Message>(Display_Error);
 }

1 个答案:

答案 0 :(得分:6)

我无法真正遵循您的示例代码 - 它没有真正解释:

  • 您如何创建HomeView
  • 如何将其信使实例传递给它。
  • 生成ApplicationError_Message消息的内容
  • 您是如何理解信息是否到达

作为一项快速测试,我在InternetMinute示例中修改了Android HomeView - 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);
        }
    }
}

这似乎工作正常 - 我得到了我期待的痕迹。

也许您的SubscribeOnMainThread没有订阅正确的消息类型 -​​ 编译器推断出什么类型?