Skip to content Skip to sidebar Skip to footer

How Pass Data Between Activities Using Rxjava In Android?

I need to pass some data between two activities MainActivity and ChildActivity. Button click on MainActivity should open ChildActivity and send event with data. I have singleton:

Solution 1:

if anybody needs a complete solution to send data between activities using RxJava2

1- Create the bus:

publicfinalclassRxBus{

privatestaticfinal BehaviorSubject<Object> behaviorSubject
        = BehaviorSubject.create();


publicstatic BehaviorSubject<Object> getSubject() {
    return behaviorSubject;
}

}

2- the sender activity

//the data to be based
                    MyData  data =getMyData();
                    RxBus.getSubject().onNext(data) ;
                    startActivity(new Intent(MainActivity.this, AnotherAct.class));

3-the receiver activity

    disposable = RxBus.getSubject().
            subscribeWith(newDisposableObserver<Object>() {


                @OverridepublicvoidonNext(Object o) {
                    if (o instanceofMyData) {
                   Log.d("tag", (MyData)o.getData();
                    }
                }

                @OverridepublicvoidonError(Throwable e) {

                }

                @OverridepublicvoidonComplete() {

                }
            });
    });

4-unSubscribe to avoid memory leacks:

@OverrideprotectedvoidonDestroy() {
    super.onDestroy();
    disposable.dispose();
}

Solution 2:

Reason:

Problem is that you are using PublishSubject. As per documentation of PublishSubject emits all the subsequent items of the source Observable at the time of the subscription. So in your case it will emit event only if it is subscribed.

Fix for your problem

Instead of using PublishSubject use BehaviorSubject which emits the most recently emitted item and all the subsequent items of the source Observable when a observer subscribe to it.

Browse following link for more details.

Post a Comment for "How Pass Data Between Activities Using Rxjava In Android?"