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

  • 相关阅读:
    mongo admin 客户端管理工具安装
    kong API gateway
    安装 docker管理 工具 页面 portainer
    elcipse 安装lombok插件解决 @Slf4j 等找不到log变量问题
    cqrs案例
    你还不知道这四点Mysql调优的话,那就赶快学起来
    python中的类型提示(type hint)
    大厂面试最常被问的Redis问题合集
    nginx gzip json [2]
    nginx gzip json 配置「1」
  • 原文地址:https://www.cnblogs.com/leo-lsw/p/otto.html
Copyright © 2011-2022 走看看