RxJS合并双Observable源并按状态过滤的代码优化问询
问题解答
当然可以实现只通过一次订阅、结合过滤操作完成需求,而且你的现有代码确实有优化空间——原代码每次处理单个用户时都重复创建Observable并执行查找逻辑,存在冗余。下面是更简洁的实现方式:
import { of, combineLatest } from 'rxjs'; import { map } from 'rxjs/operators'; type State = 'Active' | 'Inactive'; type User = { id: number; name: string; status: State }; type UserDetail = { id: number; authorizations: number }; type UserWithAuthorizations = User & UserDetail; const users: User[] = [ { id: 1, name: "John", status: "Active" }, { id: 2, name: "Mary", status: "Inactive" }, { id: 3, name: "Peter", status: "Inactive" }, { id: 4, name: "Susan", status: "Active" } ]; const authorizations: UserDetail[] = [ { id: 1, authorizations: 20 }, { id: 2, authorizations: 5 }, { id: 3, authorizations: 30 }, { id: 4, authorizations: 10 }, ]; // 定义两个基础Observable const users$ = of(users); const authorizations$ = of(authorizations); // 合并流并完成所有处理逻辑 combineLatest([users$, authorizations$]) .pipe( map(([userList, authList]) => { // 先过滤Active用户,再合并对应授权信息 return userList .filter(user => user.status === 'Active') .map(user => { const matchedAuth = authList.find(auth => auth.id === user.id); return { ...user, authorizations: matchedAuth?.authorizations || 0 // 容错处理:避免找不到授权时出错 } as UserWithAuthorizations; }); }) ) .subscribe(finalResult => console.log(finalResult));
优化说明
- 仅初始化一次基础Observable,避免重复创建流的冗余操作
- 用
combineLatest一次性合并两个数据源,全程只需要一次订阅 - 把过滤Active用户和合并授权信息的逻辑集中在一个
map操作符内,流程更清晰 - 增加了容错处理,防止出现找不到对应授权数据的异常情况
内容的提问来源于stack exchange,提问作者frankfullstack
相关产品推荐
相关产品推荐

