Rxjava2~RXbus~学渣带你扣rxjava2

作者: 品味与回味 | 来源:发表于2017-06-27 16:27 被阅读60次

public class RxBus {

public RxBus() {
}

private PublishSubject<Object> bus = PublishSubject.create();

public void send(Object o) {
    bus.onNext(o);
}

public Observable<Object> toObservable() {
    return bus;
}

public boolean hasObservers() {
    return bus.hasObservers();
}

}

在你的Application

public class MyApplication extends Application {

public static final String TAG = "MyApplication";
private RxBus bus;

@Override
public void onCreate() {
    super.onCreate();
    bus = new RxBus();
}

public RxBus bus() {
    return bus;
}

public void sendAutoEvent() {
    Observable.timer(2, TimeUnit.SECONDS)
            .subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    bus.send(new Events.AutoEvent());
                }
            });
}

}

你发送的时候
((MyApplication) getApplication()).sendAutoEvent();

需要的时候

 disposables.add(((MyApplication) getApplication())
            .bus()
            .toObservable()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object object) throws Exception {
                    if (object instanceof Events.AutoEvent) {
                        textView.setText("Auto Event Received");
                    } else if (object instanceof Events.TapEvent) {
                        textView.setText("Tap Event Received");
                    }
                }
            }));

<pre>
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MyApplication) getApplication())
.bus()
.send(new Events.TapEvent());
}
});
</pre>

相关文章

网友评论

    本文标题:Rxjava2~RXbus~学渣带你扣rxjava2

    本文链接:https://www.haomeiwen.com/subject/jeuecxtx.html