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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Rx事件总线,生命周期知道在应用程序组件之间传递数据相关的知识,希望对你有一定的参考价值。

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
    }
  
}

/**
 * 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();
            }
        }
    }

}

以上是关于java Rx事件总线,生命周期知道在应用程序组件之间传递数据的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序 组件生命周期

Vuex 注入 Vue 生命周期的过程

Formik官方应用案例解析组件生命周期事件

vue 的生命周期

微信小程序生命周期学习笔记-组件

Vue组件的生命周期