Reputation: 61
I implemented a simple event bus based on RxJava and this article: http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/
Everything works fine except I have to listen / fire events from an adapter class, which is initialized by a fragment multiple times. Because I am subscribed to each instance of that adapter, my events are being fired multiple times resulting in errors.
I would like to get subscribed to only 1 instance of that adapter and it has to be last one (not the first one). So is there a way, that in case a new instance of the adapter is spawned, I can somehow detect if I already have been subscribed and update the subscription (or delete all previous ones of that adapter and just subscribe to the current one)? Please note I also use the rxBus singleton in my other fragments / services, so I cannot just simply reset it entirely as then I will loose all other subscriptions not coming from the adapter.
Here is my code of the bus:
public class APIRxBus {
private static APIRxBus instance = null;
private final Subject<Object, Object> bus = new SerializedSubject<>(BehaviorSubject.create());
public static APIRxBus getInstance() {
if (instance == null){
instance = new APIRxBus();
}
return instance;
}
public void send(Object o) {
bus.onNext(o);
}
public Observable<Object> toObserverable() {
return bus;
}
}
and here of my subscription in the adapter class:
rxBus = APIRxBus.getInstance();
rxBus.toObserverable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Object>() {
@Override
public void call(Object event) {
if (event instanceof EVTSetPrintMode) {
//...
} else if (event instanceof EVTChangeDocumentImportance) {
//...
} else if (event instanceof EVTChangeDocumentVisibility) {
//...
}
}
});
Upvotes: 2
Views: 1730
Reputation: 69997
You could use distinctUntilChanged(Func1)
if you can tell two subsequent events are the same or not, otherwise, you could try debounce()
with some milliseconds.
Upvotes: 2