【问题标题】:RxJava Nested Observables exposing valuesRxJava 嵌套 Observables 暴露值
【发布时间】:2019-11-04 17:48:26
【问题描述】:

我有以下代码按预期工作。但是,我不喜欢blockingGet。有没有办法将 getSingle() 调用向上移动到 Observable 的“全局”变量中以避免这种情况?换句话说,我希望 getSingle 在继续代码之前完成而不使用blockingGet。请注意,在地图调用中,我需要访问 foos、bar 和 getSingle() 响应。

任何帮助将不胜感激!

public List<Baz> example(Single<Collection<Foo>> foosSingle, Collection<Bar> bars) {
  return foosSingle
    .flatMap(foos -> 
      Observable.fromIterable(bars)
        .map(bar -> getBaz(foos, getSingle(bar.getBlah()).blockingGet(), bar.getFlaz())
        .toList()
    );
}

FWIW 我尝试将 .map 调用替换为以下内容:

 .map(bar -> Lists.ArrayList(bar, getSingle(bar.getBlah()).blockingGet())
 .map(list -> getBaz(foos, list.get(1), list.get(0).getFlaz())

这让我可以访问我需要的所有变量,但它不能解决blockingGet问题。

【问题讨论】:

  • getBaz() 是做什么的?我们需要知道这个函数来重构代码

标签: rx-java rx-java2


【解决方案1】:

使用.flatMap 代替地图

public List<Baz> example(Single<Collection<Foo>> foosSingle, final Collection<Bar> bars) {
  return foosSingle
    .flatMap(foos -> 
      Observable.fromIterable(bars)
        .flatMapSingle(bar -> {
          return getSingle(bar.getBlah())
            .map(x -> getBaz(foos, x, bar.getFlaz()))
        })
        .toList()
    );
}

【讨论】:

  • 或concatMapSingle 以保留对bars 项目的响应排序。
猜你喜欢
  • 2017-01-12
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
  • 2011-08-05
相关资源
最近更新 更多