How to properly chain rxjs 6 observables?

醉酒当歌 提交于 2019-12-12 08:57:53

问题


Any suggestions, how this can be rewritten in more promise-chaining style?:

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
        map(() => {
            return this.apiService.sendGetRequest('/api/users/' + this.currentUserId).pipe(
                map(data => {
                    return this.setActiveUser(data).pipe(
                        map(() => {
                            return this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId).pipe(
                                map(tasks => {
                                    return this.taskService.setCurrentUserTasks(tasks);
                                })
                            );
                        })
                    );
                })
            );
        })
    );

回答1:


You can use switchMap for handling observables and tap for side efects handling. And you need to subscribe because it's cold observable

For error handling use catchError for all requests

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
    catchError(err=> this.errorHandler(err)),
    switchMap(() => this.apiService.sendGetRequest('/api/users/' + this.currentUserId)
        .pipe(catchError(err=> this.errorHandler(err)))
    ),
    tap(data => this.setActiveUser(data)),
    switchMap(() => this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId)
        .pipe(catchError(err=> this.errorHandler(err)))
    ),
    tap(tasks => this.taskService.setCurrentUserTasks(tasks))
).subscribe()



回答2:


use SwitchMap for that.

mainApiCall.pipe(
    switchMap(result=>secondApiCall(result)),
    switchMap(resultFromSecondApiCall=>thirdApiCall(resultFromSecond))
...
and so on
)



回答3:


Use a single pipe for your problem. Just comma seperate different chainable operators like map, switchMap, mergeMap, tap, etc.

this.apiService.sendPutRequest('/api/users/activate', usrObj).pipe(
  switchMap((results) => this.apiService.sendGetRequest('/api/users/' + this.currentUserId)),
  tap((results) => this.setActiveUser(data)),
  switchMap(() => this.apiService.sendGetRequest('api/tasks/user/' + this.currentUserId)),
  tap((results) => this.taskService.setCurrentUserTasks(tasks))
);

Simplified: Use map if you just want to transform a value without any async api calls and pass it to another operator or a subscription, tap if you just want to catch values in between without transforming (e.g. for logging). And switchMap for dispatching additional api calls.



来源:https://stackoverflow.com/questions/52774281/how-to-properly-chain-rxjs-6-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!