androidrx-java2rx-androidpublishsubject

onNext not called for PublishSubject in android, rxjava?


I am using rxjava 2 and trying to use rxbus for passing a value

rxbus code

public class SeasonTabSelectorBus {
private static SeasonTabSelectorBus instance;

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

public static SeasonTabSelectorBus instanceOf() {
    if (instance == null) {
        instance = new SeasonTabSelectorBus();
    }
    return instance;
}

public void setTab(Object object) {
    try {
        subject.onNext(object);
        subject.onComplete();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public Observable<Object> getSelectedTab() {
    return subject;
}

}

I am setting the value as

 SeasonTabSelectorBus.instanceOf().setTab(20);

This is code of my subscription

SeasonTabSelectorBus.instanceOf().getSelectedTab().subscribe(new Observer<Object>(){
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Object o) {
            if (o instanceof Integer) {
                int seasonSelected =(int) o;
                Log.e("season selected",seasonSelected+"");
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    });

Now I am getting the value on the first call, but when I call again with different values, I do not get the callback.

 SeasonTabSelectorBus.instanceOf().setTab(40);
 SeasonTabSelectorBus.instanceOf().setTab(90);
 SeasonTabSelectorBus.instanceOf().setTab(120);
 SeasonTabSelectorBus.instanceOf().setTab(290);

Solution

  • You are receiving only the first one because, after publish (subject.onNext(object)), you are calling subject.onComplete(). Just remove that line.