Rxjava2~RXbus~学渣带你扣rxjava2

public class RxBus {

public RxBus() {
}

private PublishSubject bus = PublishSubject.create();

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

public Observable 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() {
                @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() {
                @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");
                    }
                }
            }));
 
 


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

你可能感兴趣的:(Rxjava2~RXbus~学渣带你扣rxjava2)