Rx事件总线,生命周期知道在应用程序组件之间传递数据

java
阅读 31 收藏 0 点赞 0 评论 0

MainActivity.java
public class MainActivity extends AppCompatActivity implements RxBus.RxBusObserver{
  
      @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         new RxBus.RxLifeCycleObserver(this, this);
      
      //from and place in the code call
       RxBus.bus().send(YourObject);
    }
  
   @Override
    public void onNextObject(Object o) {
      //you get your data from the bus here
    }
  
}
RxBus.java

/**
 * Rx event bus that lifecycle aware to pass data between application component
 */
public class RxBus {

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

    private static RxBus rxBus;

    static {
        try {
            if (rxBus == null) {
                rxBus = new RxBus();
            }
        } catch (Exception e) {
            Timber.e(e);
        }
    }

    @NonNull
    public static RxBus bus() {
        if (rxBus != null) {
            return rxBus;
        } else {
            return new RxBus();
        }
    }

    public void send(Object o) {
        if (o != null) {
            bus.onNext(o);
        }
    }

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

    public interface RxBusObserver {
        void onNextObject(Object o);
    }

    /**
     * Handle subscribe and un subscribe to avoid memory leak
     */
    public static class RxLifeCycleObserver implements LifecycleObserver {

        private CompositeDisposable compositeDisposable = new CompositeDisposable();

        private RxBusObserver rxBusObserver;

        private RxBus bus;

        public RxLifeCycleObserver(LifecycleOwner lifecycleOwner, RxBusObserver rxBusObserver) {
            this.rxBusObserver = rxBusObserver;
            this.bus = RxBus.bus();
            lifecycleOwner.getLifecycle().addObserver(this);
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        void start() {
            if (compositeDisposable != null) {
                compositeDisposable.add(bus.toObservable()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(o -> {
                            if (rxBusObserver != null) {
                                rxBusObserver.onNextObject(o);
                            }
                        }, Timber::e));
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        void stop() {
            if (compositeDisposable != null) {
                compositeDisposable.clear();
            }
        }
    }

}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号