Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RX sub observable - execute only once

Normally I use

Observable observable = someObservable.replay().refCount();

to create an observable, that is executed only once. This works fine if I subscribe to observable multiple times like following:

observable.observeOn(Schedulers.io())
    .subscribeOn(AndroidSchedulers.mainThread())
    .subscribe(...);

observable.observeOn(Schedulers.io())
    .subscribeOn(AndroidSchedulers.mainThread())
    .subscribe(...);

The observable is only executed once - perfect, just as I want it. If I now do following:

Observable obs1 = observable.map(...); // call some operators
Observable obs2 = observable.map(...); // call some operators

obs1.observeOn(Schedulers.io())
    .subscribeOn(AndroidSchedulers.mainThread())
    .subscribe(...);

obs2.observeOn(Schedulers.io())
    .subscribeOn(AndroidSchedulers.mainThread())
    .subscribe(...);

Then the observable is executed twice. How can I make sure, that this won't happen?

like image 289
prom85 Avatar asked Sep 06 '16 18:09

prom85


1 Answers

I think what you want is to add a .take(1) operator. This way once something is read from the observable it will call onComplete.

like image 119
FriendlyMikhail Avatar answered Nov 06 '22 01:11

FriendlyMikhail