Reputation: 17828
Here's a simple observable example:
observable
.filter(...)
.buffer(50, TimeUnit.MILLISECONDS)
.doOnNext(/* this is executed all the time... */)
.filter(data -> data.size() > 0)
.doOnNext(/* this is not executed because of the filter above... */)
.flatMap(data -> Observable.from(data).distinctUntilChanged())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
Problem/Question
The observable that I get from the buffer(...)
function is emitting result after result, mostly empty ones.
Is filtering the correct way to handle this problem with observables like this? Will having a lot of such subscriptions at the same time cost performance? Or should this be handled differently?
Upvotes: 1
Views: 90
Reputation: 69997
Generally, yes, filter out what you don't need downstream.
Will having a lot of such subscriptions at the same time cost performance?
Technically: yes. More timers, more active sequences on the computation thread. However, the overhead of the sequence may be far less than the business logic you execute.
To save on some overhead, I'd use flatMapIterable
:
observable
.filter(...)
.buffer(50, TimeUnit.MILLISECONDS)
.doOnNext(/* this is executed all the time... */)
.filter(data -> data.size() > 0)
.doOnNext(/* this is not executed because of the filter above... */)
.flatMapIterable(data -> data) // <-----------------------------
.distinctUntilChanged()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
Upvotes: 1