RxJava 将 Observable 与另一个可选的 Observable 与超时结合 [英] RxJava combine Observable with another optional Observable with timeout

查看:90
本文介绍了RxJava 将 Observable 与另一个可选的 Observable 与超时结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个 observables AB.A 肯定会发布结果,而 B 的结果可能根本不会发布(超时).

Asume we have two observables A and B. A publishes a result certainly, while the result from B might not be published at all (timeout).

问题是如果 B 在一个时间范围内返回,如何映射 AB 的结果,否则只返回 AB 的结果代码>A.

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.

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

地图示例:

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

推荐答案

为了超时 <​​code>B observable 使用 take 操作符和时间参数:

In order to timeout B observable use take operator with time argument:

B.take(10, TimeUnit.SECONDS)

为了接收 AB(如果 B 在超时内准备好)使用 concatWith:

In order to receive either A or B (if B is ready within timeout) use concatWith:

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

如果您希望组合 AB(可选地用 B 丰富 A):

In case you wish to combine A and B (optionally enrich A with B):

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

如果 AB 属于不同类型(可选地用 B 丰富 A):

In case A and B are of different types (optionally enrich A with B):

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

这篇关于RxJava 将 Observable 与另一个可选的 Observable 与超时结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆