简体   繁体   English

如果延迟很大,如何在情感之间的Observable上运行函数?

[英]How to run a function on an Observable between item emotion if there was a big delay?

I have a PublishSubject which receive emits from UI: 我有一个PublishSubject,它接收来自UI的发射:

myPublishSubject
        .map {
            ...
        }
        .doOnNext {
            // using emitted item
        }
        .timeout (...) // wait for the gap!
        .doOnNext {
            // running a function after a specific gap between two item
        }
        .subscribe()

I want to wait a specific amount of time after last emit (not onComplete, cause it continue emitting later) and run a function. 我想在上一次发出后等待特定的时间(不是onComplete,导致它以后继续发出)并运行一个函数。 It can be interpreted as a gap between item emotion. 可以将其解释为项目情感之间的差距。

I am looking for something like timeout but this method issue is it kills the Observable with error. 我正在寻找timeout东西,但是此方法的问题是它杀死了带错误的Observable。

You have to be a bit creative with publish and switchMap for example: 您必须对publishswitchMap ,例如:

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

ps.publish(o -> 
    o.mergeWith(
        o.switchMap(e -> 
             Observable.just(1).delay(200, TimeUnit.MILLISECONDS)
            .ignoreElements()
            .doOnCompleted(() -> System.out.println("Timeout action: " + e))
        )
    )
).subscribe(System.out::println);

ps.onNext(1);
ps.onNext(2);

Thread.sleep(100);

ps.onNext(3);

Thread.sleep(250);

ps.onNext(4);

Thread.sleep(250);

It works by sharing a source and routing into two ways, one is directly emitting while the other feeds a switchMap that when receives a new item, starts a delayed Observable and reacts to its completion (ignoring the original trigger element to avoid duplicate events due to mergeWith ). 它通过共享一个源和路由以两种方式工作,一种是直接发出,而另一种则是提供一个switchMap ,当接收到一个新项时,它会启动一个延迟的Observable并对其完成做出反应(忽略原始触发器元素,以避免由于mergeWith )。 When there is a new signal during the grace period, switchMap will cancel the previous delay and start with the newer delay. 在宽限期内出现新信号时, switchMap将取消先前的延迟,并从新的延迟开始。

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

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