简体   繁体   English

RxJava 将 Observable 与另一个可选的 Observable 结合使用,并带有超时

[英]RxJava combine Observable with another optional Observable with timeout

Asume we have two observables A and B .假设我们有两个 observables AB A publishes a result certainly, while the result from B might not be published at all (timeout). A肯定会发布结果,而B的结果可能根本不会发布(超时)。

The question is how to map the result from A and B if B returns within a timeframe, otherwise just return the result from A .问题是如果B在一个时间范围内返回,如何映射AB的结果,否则只返回A的结果。

Observable<DatabaseObject> A = getDatabaseElement();
Observable<NetworkObject> B = restApi.getElement();

Map example:地图示例:

map((databaseObject, networkObject) => {
  databaseObject.setData(networkObject);
  return databaseObject;
})

In order to timeout B observable use take operator with time argument:为了使B observable 超时,请使用带时间参数的take运算符:

B.take(10, TimeUnit.SECONDS)

In order to receive either A or B (if B is ready within timeout) use concatWith :为了接收AB (如果B在超时内准备好)使用concatWith

A.concatWith(B.take(10, TimeUnit.SECONDS))
    .takeLast(1)

In case you wish to combine A and B (optionally enrich A with B ):如果您希望组合AB (可选地用B丰富A ):

A.concatWith(B.take(10, TimeUnit.SECONDS))
    .reduce((a, b) -> a.setData(b))

In case A and B are of different types (optionally enrich A with B ):如果AB属于不同类型(可选地用B丰富A ):

Observable.combineLatest(
    A,
    B.take(10, TimeUnit.SECONDS).defaultIfEmpty(stubB)),
    (a, b) -> { if (b != stubB) a.setData(b); }
)

You might want to take a different approach here .. There is an operator designed exactly for the behavior you described.您可能想在这里采用不同的方法.. 有一个专门为您描述的行为设计的运算符。 Take a look at .timeout(long time, TimeUnits units, Observable backupObservable) which instructs a stream to switch from the original observable (in your case B, the network request I assume) to the backup A observable when there are no other items in the original stream for the specified amount of time.看一看.timeout(long time, TimeUnits units, Observable backupObservable)它指示流从原始 observable(在您的情况 B,我假设的网络请求)切换到备份 A observable,当其中没有其他项目时指定时间量的原始流。

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

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