如何在 rxjs 6 中将 combineLatest 与 flatMap 结合使用?

How to use combineLatest with flatMap in rxjs6?

我在 React Native 中使用 rxjs 5.5.12 的代码,它有效。

在 rxjs 5.5.12 中:

// the function will return Observable
  rxInit() {
    return Observable.combineLatest(
      myObservable1,
      myObservable2,
    ).flatMap((result) => {
      console.log('rxInit result =>', result) // I can see the result
      const [token, email] = result

      this.token = token
      this.email = email

      // check the value is empty or not and return Observable.

      if (this.token != null && this.email != null) {
        return Observable.fromPromise(myApiPromise).catch(handleErrorFunction)
      } else if (this.token != null && this.uid != null) {
        return Observable.fromPromise(myApiPromise).catch(handleErrorFunction)
      } else {
        return Observable.of(null)
      }
    })
  }

在 rxjs 6.5.3 中:

先导入一些运算符:

import { combineLatest } from 'rxjs';
import { flatMap } from 'rxjs/operators';

我修改代码:

rxInit() {
  console.log('rxInit start');

  return combineLatest(
    myObservable1,
    myObservable2
   ).flatMap((result) => {
     console.log('rxInit result =>', result)
   });

   console.log('rxInit end');
 }

会显示错误TypeError: (0 , _rxjs.combineLatest)(...).flatMap is not a function

所以我注意到可能我必须使用 pipe,我尝试更改代码。

rxInit() {
    console.log('rxInit start'); // it works.

    return combineLatest(
      myObservable1,
      myObservable2
    ).pipe(flatMap((result) => {
      console.log('rxInit result =>', result);  // the console log doesn't work
    }));
    console.log('rxInit end'); // the console log doesn't work
  }

我不知道为什么我无法在 console.log 中得到结果。

如有任何帮助,我们将不胜感激。

看起来您没有return从 flatMap() 获取任何内容,mergeMap 在 rxjs 中用于支持 flatMap 顺便说一下。您需要 return 一个可观察对象。

return combineLatest(
  myObservable1,
  myObservable2
).pipe(mergeMap((result) => {
  console.log('rxInit result =>', result);  // the console log doesn't work
  return of(result)
}));