简体   繁体   English

RxJava一次只执行一个Observable

[英]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. 编辑1:这是我尝试过的。 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 : PublishSubjectswitchMap PublishSubject使用:

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). 为了充分利用这个networkOperationObservable将明确响应unsubscribe调用(如关闭Socket或其他)。 Observable.using is the tool of choice for that generally. Observable.using一般是选择的工具。

PublishSubject is exactly what you need. PublishSubject正是您所需要的。 It is an Observable you can add events to at any time. 它是一个Observable您可以随时添加事件。

Create it: 创造它:

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

Then use Observable.throttleWithTimeout() operator: 然后使用Observable.throttleWithTimeout()运算符:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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