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描述符,方法名任意

  • 相关阅读:
    第一次上传文件到linux服务器
    @JsonFormat与@DateTimeFormat的区别
    Tomcat端口被占用处理
    简单的Tomcat部署
    PHP源码加密,zend guard与ioncube
    PHP计算年龄
    My97DatePicker时间控件 JQuery UI
    php二维数组自定义排序
    CodeSmith Generator 7.0.2激活步骤
    SQL Server Management Studio 2008版本的安装
  • 原文地址:https://www.cnblogs.com/leo-lsw/p/otto.html
Copyright © 2011-2022 走看看