zoukankan      html  css  js  c++  java
  • Otto:EventBus

    OttoEventBus

    2014年6月20日 星期五

    15:14

    参考: http://www.mythroad.net/?p=4151

    Otto 是Android系统的一个Event Bus模式类库。用来简化应用组件间的通信.

    主要使用的类有com.squareup.otto.Bus类、@Produce@Subscribe注解

    @Subscribe 注解告诉Bus该函数订阅了一个事件,该事件的类型为该函数的参数类型;

    @Produce注解告诉Bus该函数是一个事件产生者,产生的事件类型为该函数的返回值。

    可以在Activity或者FragmentonResume中注册监听器,在onPause中取消注册:

     @Override protected void onResume() {
        super.onResume();

    // Register outselves so that we can provide the initial value.
        BusProvider.getInstance().register(this);
      }

    @Override protected void onPause() {
        super.onPause();

    // Always unregister when an object no longer should be on the bus.
        BusProvider.getInstance().unregister(this);
      }

    在一个位置定义生产函数:@Produce

      @Produce public LocationChangedEvent produceLocationEvent() {
        // Provide an initial value for location based on the last known position.
        return new LocationChangedEvent(lastLatitude, lastLongitude);
      }

    在需要订阅该事件的地方捕获该事件:@Subscribe

     @Subscribe public void onLocationChanged(LocationChangedEvent event) {

      }

    不管是生产者还是订阅者都需要向Bus注册自己:

    Bus.register(this);

    Otto的事件调用默认在主线程(应用的UI线程):

    下面的效果是一样的
    Bus bus1 = new Bus();
    Bus bus2 = new Bus(ThreadEnforcer.MAIN);

    如果不关系在哪个线程中执行:可以通过ThreadEnforcer.ANY指定

    还可以通过ThreadEnforcer接口自定义线程模型

    生产(发布):bus.post(new AnswerAvailableEvent(42));

    Posting是同步的,所以程序执行时保证所有的订阅者都准确被调用

    订阅:@Subscribe,仅包含一个参数,public描述符,方法名任意

  • 相关阅读:
    JavaEE各种Javadoc的下载
    Failed to stop Abandoned connection cleanup thread
    检查Encoding-name是否合法
    flex 实现图片播放 方案一 图片全部预加载放内存
    Example 2
    ncl 实例参考
    flex 动画笔记
    Example 1
    给DBGrid动态赋值后,如何用程序指定某行某列为当前焦点?(100分)
    能详细说一下action:=cafree这句吗?好多书都没说清楚!
  • 原文地址:https://www.cnblogs.com/leo-lsw/p/otto.html
Copyright © 2011-2022 走看看