Search code examples
javascriptrxjsrxjs6

How to use withLatestFrom with a promise?


Why isn't it possible to convert a promise to an observable and then use it with withLatestFrom. It's not clear to me, why this doesn't resolve.

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

Solution

  • WithLatestFrom emits only when its source Observable emits, since of('') emits before the source to withLatestFrom, your withLatestFrom is never triggered.

    The following code will not work:

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

    but this will:

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