如何在RxJava中为某些项添加延迟

huangapple go评论70阅读模式
英文:

How to add delay for some items in RxJava

问题

我想为以下目的实现一个 RxChain:

一个可观察的源正在发出两种类型的数据(S、E)。现在,我想要一个可观察的/可流式的对象,它将立即发出所有的 S,但是如果在此期间没有 S 发出,它应该在第一个 E 发出后的给定延迟(10 秒)后发出最新的 E。

如何在RxJava中为某些项添加延迟

英文:

I want to implement a RxChain for the following purpose:

An observable source is emitting two types of data (S, E). Now I want an observable/flowable which will emit all the S immediately but it should emit the latest E after a given delay (10 sec) from the first emission of E if no S comes in the meantime.

如何在RxJava中为某些项添加延迟

答案1

得分: 1

代替只有一个可观察的源同时发出S和E的做法,你可以将它们拆分为两个可观察的对象,在“E流”上添加一个10秒的throttleLast,然后将它们合并在一起。

例如:

Observable<String> sStream = source.filter(x -> x.type == Types.S);
Observable<String> eStream = source.filter(x -> x.type == Types.E).throttleLast(10, TimeUnit.SECONDS);

Observable.merge(sStream, eStream).subscribe(...);
英文:

Instead of having 1 observable source emitting both S and E, you could instead split them into 2 observables, add a throttleLast 10s on the "E stream" and then merge them together

e.g.

Observable&lt;String&gt; sStream = source.filter(x -&gt; x.type == Types.S);
Observable&lt;String&gt; eStream = source.filter(x -&gt; x.type == Types.E).throttleLast(10, TimeUnit.SECONDS);


Observable.merge(sStream, eStream).subscribe(...);

huangapple
  • 本文由 发表于 2020年8月15日 00:52:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63416986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定