首页 > 解决方案 > Rxjava2如何简洁地将结果从前一个节点返回到链中的下一个节点

问题描述

我在android中使用rxjava2,有时会遇到这样的问题:

Observable.fromArray(
         // maybe a list about photo url in SDCard
    )
    .flatMap(
         // make list to single and upload to server,
         // use retrofit observable<uploadResponse>
    )
    .map(uploadResponse -> {
        // *Problem of point
    })
    .map(
        // in this map I want to get this single photo url in SDCard
        // and some info from uploadResponse,how to do in 
        // *Problem of point of previous map?
     );

这段代码忽略了一些线程切换和其他不重要的步骤。这个问题也让我对 nodejs 的 Promise 感到困惑,如何将一些值传递给链的每一步?我在 firebase 上使用 nodejs 的 version6,它不支持等待。

标签: node.jsfirebasepromiserx-java2

解决方案


至于问题的 JavaScript 部分,可以通过以下方式方便地解决async..await

(async () => {
  const foo = await fooPromise;
  const bar = await getBarPromise(foo);
  const baz = await getBazPromise(bar);
})()
.catch(console.error);

我在firebase上使用nodejs的版本6,它不支持等待。

自从 Node 4 中出现生成器以来,背后的模式async..await就被广泛使用。同样的事情可以用co最著名的实现来实现:

const co = require('co');

co(function * () {
  const foo = yield fooPromise;
  const bar = yield getBarPromise(foo);
  const baz = yield getBazPromise(bar);
})
.catch(console.error);

由于asyncfunction 是 promise 的语法糖,因此asyncfunction 所做的一切都可以仅用 promise 重写。

鉴于以后可能需要一个值(foo):

fooPromise
.then(foo => getBarPromise(foo))
.then(bar => getBazPromise(bar))
.then(baz => {
  // foo and baz are needed here
});

它应该与其他结果一起通过链:

fooPromise
.then(foo => {
  return getBarPromise(foo).then(bar => ({ foo, bar }));
})
.then(({ foo, bar }) => {
  return getBazPromise(bar).then(baz => ({ foo, baz }));
})
.then(({ foo, baz }) => {
  // foo and baz are destructured from the result
});

或者应该嵌套承诺以便foo在当前函数范围内可用:

fooPromise
.then(foo => {
  return getBarPromise(foo)
  .then(bar => getBazPromise(bar))
  .then(baz => {
    // foo and baz are available here
  })
});

相同的配方适用于其他 API 和语言。例如,RxJS:

fooObservable
.flatMap(foo => Observable.zip(
  Observable.of(foo),
  getBarObservable(foo)
))
.map(([foo, bar]) => {
  // foo and bar are destructured from the result
})

推荐阅读