Passing through multiple parameters to rxjs operat

2019-04-27 22:49发布

Is there a more elegant way of doing the following?

private getHeaders(): Observable<any> {
  let version;
  let token;
  return this.appInfo.getVersion()
    .pipe(
      tap(appVersion => version = appVersion),
      mergeMap(() => this.storage.get('access_token')),
      tap(accessToken => token = accessToken),
      mergeMap(accessToken => of(this.createHeaders(version, token)))
    );
}

How can I more fluently remember the two return values of this.appInfo.getVersion() and this.storage.get('access_token') without writing them to temporary variables with the power of rxjs?

Perhaps merging some observables into one? There are so many rxjs operators and stuff...

3条回答
叛逆
2楼-- · 2019-04-27 23:10

Using forkJoin:

.pipe(
  mergeMap((appVersion) => forkJoin(
    of(appVersion),
    this.storage.get('access_token').take(1)
  )),
  mergeMap(([version, token]) => {
    this.createHeaders(version, token)
  })
)

But even easier with withLatestFrom:

.pipe(
  withLatestFrom(this.storage.get('access_token')),
  mergeMap(([version, token]) => {
    this.createHeaders(version, token)
  })
)

I have included both because withLatestFrom is easier but forkJoin should be used where you need to access the initial parameter. For example, if you were doing this.storage.get(appVersion)

查看更多
来,给爷笑一个
3楼-- · 2019-04-27 23:18

Use forkJoin, it's designed for this type of situation.

查看更多
4楼-- · 2019-04-27 23:29

You may want to try something like this

private getHeaders(): Observable<any> {
  return this.appInfo.getVersion()
    .pipe(
      mergeMap(version => this.storage.get('access_token')
                          .map(token => ({version, token})),
      map(data => this.createHeaders(data.version, data.token))
    );
}

ALTERNATIVE VERSION WITH ZIP

private getHeaders(): Observable<any> {
  const versionObs = this.appInfo.getVersion();
  const tokenObs = this.storage.get('access_token');
  return Observable.zip(versionObs, tokenObs)
    .pipe(
      map(data => this.createHeaders(data[0], data[1]))
    );
}
查看更多
登录 后发表回答