0
点赞
收藏
分享

微信扫一扫

Otto:更神奇的观察者模式(1)----使用方法

介绍

是square公司出的一个事件库(pub/sub模式),用来简化应用程序组件之间的通讯。

square官方对于这个库的解释原文如下:

所以可以定义:Otto 修改自Google的Guava库,专门为Android平台进行了优化。
有兴趣学习源码的小伙伴,可以直接戳这里:
Otto https://github.com/square/otto

使用

Otto本身是为Android平台专门开发的,建议在使用的时候使用单例模式

**
     * Get the instance of {@link Bus}
     *
     * @return
     */
    public static synchronized Bus get() {
        if (sBus == null) {
            sBus = new Bus(ThreadEnforcer.ANY);
        }
        return sBus;
    }

当然,这算是比较low一点的单例模式,高级一点的可以使用相应的一些注解annotation来更加便捷的实现,这里只是入门使用的方法解析,我们不予讲解。

注册

otto中第一步就是注册,我们需要在使用的Activity或Fragment等控件中注册,位置可以随意,但是建议与生命周期同步。这样可以伴随生命周期进行注册和撤销注册。

Actvity中使用

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       //todo dosomething here
        RxBus.get().register(this);
       //todo dosomething here
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //todo dosomething here
        RxBus.get().unregister(this);
       //todo dosomething here
    }

Fragment中使用

 @Nullable
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
           //todo dosomething here
          RxBus.get().unregister(this);
          //todo dosomething here
    }


    @Override
    protected void onDestroyView() {
        super.onDestroyView();
        //todo dosomething here
        RxBus.get().unregister(this);
       //todo dosomething here
    }

这里楼主是使用的RxBus来做的demo和代码演示,具体的用法具体根据各自业务分析。在onCreate中注册和在onDestroy中取消,将整个事件处理逻辑和生命周期绑定在一起

发送事件

发送事件就非常轻松,只需要调用Bus的post方法即可

普通用法

/**
*  event的对象必须跟订阅事件的对象相同
* 例如:RxBus.get().post("我要吃饭了");
* 订阅事件必须为 
* @Subscribe
*     public void eat(String food) {
*        // purpose
*      
*     }
* 其中监听对象和订阅对象均为String类型
*/
RxBus.get().post(Object event)

高级用法plus

/**
*  event的对象必须跟订阅事件的对象相同
* 例如:RxBus.get().post("我要吃饭了");
* 订阅事件必须为 
*   @Subscribe(
*           thread = EventThread.IO,
*           tags = {                    @Tag("i love you")
*           }
*    )
*   public void eatMore(final ArrayList<String> foods) {
*        //线程为IO线程,无法做UI更新,需要切回主进程
*       runOnUiThread(new Runnable() {
*           @Override
*            public void run() {
 *               BaseUtils.Toast(foods);            }
 *       });
 *       Log.log(foods);
 *  }
* 其中监听对象和订阅对象均为list类型,且tag为“i love you”
*/
RxBus.get().post(“i love you”,list);

订阅事件

订阅事件需要用到@Subscribe这个注解,我们废话少说,直接上代码:

简单用法

 @Subscribe
    public void eat(String food) {
        // purpose
        BaseUtils.Toast(food);
        Log.log(food);
    }

高级用法plus

/**
     * thread为进程,这里指定为IO进程
     * tags 为标签,需要在特定的情况下使用
     * @param foods
     */
  @Subscribe(
            thread = EventThread.IO,
            tags = {
                    @Tag("i love you")
            }
    )
   public void eatMore(final ArrayList<String> foods) {
        //线程为IO线程,无法做UI更新,需要切回主进程
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                BaseUtils.Toast(foods);
            }
        });
        Log.log(foods);
    }

生产者

说道这里,大家会觉得这有什么难的,那么我们的重点就来了,也就是OTTO的超级奥义 @Produce,正如名字翻译,生产者,这里可以用来做一些内容提供。
有时候当用户订阅某个事件的时候,希望能够获取当前的一个对象(可以为值,也可为一个对象,甚至一个集合,这里用对象来代替称呼)。
同时,如果该对象发生变化的时候,会自动通知所有订阅该对象的类更新对应的@Subscribe方法。废话不多说,直接上代码。


    @Produce
    public String produceFood() {
        return "hello world!";
    }

 @Produce(
            thread = EventThread.IO,
            tags = {
                    @Tag(BusAction.EAT_MORE)
            }
    )
    public ArrayList<String> produceMoreFood(){
        ArrayList<String> list=new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        return list;
    }

该方法会在register方法被调用后,直接提供内容去更新相应的模块

举报

相关推荐

0 条评论