简体   繁体   中英

RxJava execute only one Observable at a time

We have window with search field. Every time user inputs something search is performed.

  1. Search event is translated to data stream.

  2. On every new search we need to start async network operation and close previous. How to archive this effect?

Edit1: Here's what I've tried. It executes all observables! Not the only last one, where is a mistake?

PublishSubject<Integer> subject = PublishSubject.create();

subject.switchMap(integer -> Observable.fromCallable(() -> {
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "-" + integer + "-";
})).subscribe(s -> System.out.print(s));
for (int i = 0; i < 30; i++) subject.onNext(i);

Use PublishSubject with switchMap :

PublishSubject<String> subject = PublishSubject.create();
subject
  .switchMap(
    x -> networkOperationObservable(x)
           .subscribeOn(Schedulers.io))
  .subscribe(subscriber);

To get the most out of this networkOperationObservable would respond sensibly to an unsubscribe call (as in close the Socket or whatever). Observable.using is the tool of choice for that generally.

PublishSubject is exactly what you need. It is an Observable you can add events to at any time.

Create it:

private Subject<String, String> filteringSubject = PublishSubject.create();

Then use Observable.throttleWithTimeout() operator:

Subscriber<String> filteringSubscriber = new DefaultSubscriber<>();
filteringSubject
    .throttleWithTimeout(250, TimeUnit.MILLISECONDS)
    .doOnNext(new Action1<String>() {
        @Override
        public void call(String text) {
            //make a network call
        }
     })
     .subscribe(filteringSubscriber);

Usage:

filteringSubject.onNext(text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM