Reputation: 2856
I'm starting using RxAndroid in my existing application. I've started with a quite simple activity where I have a search field and I contact an API using Retrofit when the text changes. I also want to cancel the current unfinished request if there's one before starting a new one. Here is what I have so far:
private Subscription currentRequestSubscription = null;
// Create stream of filtered queries
Observable<String> queryObservable = RxTextView.textChanges(searchView)
.startWith("")
.debounce(DELAY_BEFORE_REQUEST, TimeUnit.MILLISECONDS)
.map(new Func1<CharSequence, String>() {
@Override
public String call(CharSequence charSequence) {
return charSequence.toString();
}
})
// Make search request and update UI
queryObservable.observeOn(Schedulers.io())
.subscribe(new Action1<String>() {
@Override
public void call(String query) {
if (currentRequestSubscription != null) {
currentRequestSubscription.unsubscribe();
}
currentRequestSubscription = createAPIRequestObservable(query)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(... update UI with results ...);
}
});
I feel like storing the subscription is not really reactive programming compliant. How could I do this in a more standard way?
Upvotes: 1
Views: 1116
Reputation: 15824
No need to create a new subscription each time in this case, switchMap
can take care of unsubscribing from the old observable when a new comes in. Something like this:
currentRequestSubscription = RxTextView.textChanges(searchView)
.observeOn(Schedulers.io())
.startWith("")
.debounce(DELAY_BEFORE_REQUEST, TimeUnit.MILLISECONDS)
.map(CharSequence::toString)
.switchMap(text -> createAPIRequestObservable(text).subscribeOn(Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(/*... update UI with results ...*/);
Also good example.
Upvotes: 5