Ahmed-Abdelmeged
11/19/2017 - 7:53 PM

Rx event bus that lifecycle aware to pass data between application component

Rx event bus that lifecycle aware to pass data between application component

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

}