RxBus使用示例

来源:互联网 发布:模块化编程的好处 编辑:程序博客网 时间:2024/06/12 22:18

首先导入rxjava,rxAndroid,rxlifecycle

compile 'io.reactivex:rxandroid:latest.release'compile 'io.reactivex:rxjava:latest.release'compile 'com.trello:rxlifecycle:latest.release'compile 'com.trello:rxlifecyclecomponents:latest.release'

为什么要导入rxlifecycle?因为用rxlifecycle可以很省事的解决了rxbus的unregiste问题

接下来看rxbus代码:

1.先创建 _bus

private final Subject<Object, Object> _bus;private volatile static RxBus instace;    public RxBus() {        _bus = new SerializedSubject<>(PublishSubject.create());    }


2.然后创建一个单列模式

 public static RxBus getBus() {        if (instace == null) {            synchronized (RxBus.class) {                if (instace == null)                    instace = new RxBus();            }        }        return instace;    }

3.接下来就是核心功能了:

 public void send(Object o) {        _bus.onNext(o);    }    /**     * dosen't designation to use specail thread,It's depending on what the 'send' method use     * @param lifecycleTransformer rxlifecycle     * @return     */    public Observable<Object> toObserverable(LifecycleTransformer lifecycleTransformer) {        return _bus.compose(lifecycleTransformer);    }    /**     * designation use the MainThread, whatever the 'send' method use     * @param lifecycleTransformer rxlifecycle     * @return     */    public Observable<Object> toMainThreadObserverable(LifecycleTransformer lifecycleTransformer) {        return _bus.observeOn(AndroidSchedulers.mainThread()).compose(lifecycleTransformer);    }

‘send’ Method 不用说了,类似otto的post,用于发送事件;而toObserverable 就是用来接收事件的,
为什么还有个toMainThreadObserverable呢,因为当你使用send 发送事件的时候有可能不是在主线程里发送的,而你的toObserverable里的某些事件却有可能需要在主线程里执行,比如更新view;所以就需要个toMainThreadObserverable不论send在什么线程里执行的,到这里都是转到主线程里;

下面介绍使用方法:
1.首先你必须创建一个event类,来区分事件:

public class MainActivityEvent {    String value;    public String getValue() {        return value;    }    public void setValue(String value) {        this.value = value;    }}

2.然后就是send

 MainActivityEvent mainActivityEvent = new MainActivityEvent();mainActivityEvent.setValue("Hello");RxBus.getBus().send(mainActivityEvent);

3.接收端:

        RxBus.getBus().toObserverable(bindUntilEvent(ActivityEvent.DESTROY))                .subscribe(new Action1<Object>() {                    @Override                    public void call(Object event) {                        if(event instanceof MainActivityEvent){                            MainActivityEvent mainActivityEvent = (MainActivityEvent) event;//                            Toast.makeText(getApplicationContext(),mainActivityEvent.getValue(),Toast.LENGTH_SHORT).show();                            Log.d(TAG, "call: "+((MainActivityEvent) event).getValue());                        }                    }                });

这里的bindUntilEvent(ActivityEvent.DESTROY)是我使用了rxlifecycle的RxAppCompatActivity

一个简单的rxbus示例就完成了

本文demo源码

1 0
原创粉丝点击