【问题标题】:How to use withLatestFrom with a promise?如何与承诺一起使用 withLatestFrom?
【发布时间】:2020-12-02 15:39:30
【问题描述】:

为什么不能将promise 转换为observable,然后将其与withLatestFrom 一起使用。我不清楚,为什么这不能解决。

of('')
  .pipe(
    withLatestFrom(from(myPromise)),
    map((res) => {
      console.log('does not resolve', res);
    })
  )
  .subscribe();

【问题讨论】:

  • 可以将withLatestFrom 与promise 一起使用。你需要制作一个可重现的演示,因为不可能给出这样的建议。
  • @martin 我提供了一个演示,我有一个承诺,我希望使用 withLatestFrom 在 map 函数中使用解析的值,这样我就可以访问这两个值(来自可观察源的值和来自承诺)。我不确定你要什么?

标签: javascript rxjs rxjs6


【解决方案1】:

WithLatestFrom 仅在其源 Observable 发出时发出,因为of('') 在源到 withLatestFrom 之前发出,所以您的 withLatestFrom 永远不会被触发。

以下代码将不起作用:

of('1 + 1')
  .pipe(
    withLatestFrom(new Promise(x => x("== 2"))),
    map(([res1,res2]) => console.log(res1, res2))
  )
  .subscribe();

但这会:

of('1 + 1')
  .pipe(
    delay(100), // <= delay source execution
    withLatestFrom(new Promise(x => x("== 2"))),
    map(([res1,res2]) => console.log(res1, res2))
  )
  .subscribe();

【讨论】:

  • 关于如何在不使用丑陋的 hack 作为延迟的情况下获取源 observable 的值和 map 函数中的 promise 值的任何建议。
  • 您可以使用observeOn(asyncScheduler) 强制of('') 异步运行,或者考虑使用combineLatest 运算符
【解决方案2】:

这是withLatestFrom 的预期行为。源 observable 在 Promise 解析之前同步完成(异步)。 withLatestFrom 仅在两个 observable 都至少发出一次后才发出,然后仅在源 observable 发出时才发出。

在您的情况下,源 observable 在 promise 解决之前就已完成。

of('').pipe(
  delay(100),
  withLatestFrom(from(myPromise)),
  tap(res =>
    console.log('should resolve', res)
  )
).subscribe();

更新 #1:没有delay 的解决方案

如果两个源 observable 都发出一次并完成,那么forkJoin 是最好的

forkJoin({
  addition: of(1 + 1),
  promise: from(myPromise)
}).pipe(
  map(({addition, promise}) => {return /* something */})
)

combineLatest 类似于forkJoin,但它更适用于持续发射值的长寿命流。它等待其内部流全部开始发射,然后发射所有最新值。

combineLatest(
  of(1 + 1),
  from(myPromise)
).pipe(
  map(([addition, promise]) => {return /* something */})
)

或者,如果您想使用 withLatestFrom 并且您对时间限制感到满意。

from(myPromise).pipe(
  withLatestFrom(of(1+1)),
  map(([promise, addition]) => {return /* something */})
)

应该可以。

【讨论】:

  • @mnewmedia 添加了一些示例,说明如何在不使用 delay 的情况下执行此操作
猜你喜欢
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多