ali*_*ani 5 javascript functional-programming rxjs lodash
我知道 rxjs 和 lodash 的定义和职责,但我想知道:当我在我的项目中使用 rxjs 时,我可以扔掉 lodash 吗?因为 rxjs 可以同步和异步工作(异步和同步数据)。我认为它可以作为 lodash 的替代品。我对吗?
这取决于你做什么。有些任务两者都可以完成,但许多任务只能由两者之一完成。RxJS 并不是 Lodash 的替代品。
请注意,他们有完全不同的使命:
它们是完全不同的东西。但我确实理解这种困惑:它们看起来很相似,但要做的事情却截然不同。
Lodash:可以与.Net中的Linq进行比较。这一切都是关于导航、组合和操作列表或可枚举的事物。
Rxjs:不是关于列表,而是关于随着时间的推移发生的事件。
使用它们实际上是有意义的:
// every time filter criteria is updated on the GUI, this will emit a new set of filtercriteria
let filterCriteria$ = new BehaviorSubject<FilterCriteria>({});
// this gets the list of employees, but will also emit a new set of employees when there are any changes
let mostRecentListOfEmployees$: Observable<Employee[]> = this.apiService.GetEmployees();
// using combineLatest will make sure that the map operator is executed every time the criteria or the list is updated
let filteredEmployees$ = filterCriteria$.pipe(
combineLatest(mostRecentListOfEmployees$),
map(([filterCriteria, list]) => {
// this is pseudocode, not sure about the exact lodash syntax for filtering ...
return _.filter(list, filterCriteria);
})
)
Run Code Online (Sandbox Code Playgroud)
每次更新过滤条件时以及当一组新员工通过 api 进入时,您将依赖 Rxjs 重新过滤列表。
Lodash 将用于对阵列进行实际过滤。
您的 GUI 将订阅 FilteredEmployees$ observable。
如果这种方法看起来不熟悉,这就是所谓的响应式编程: https: //en.wikipedia.org/wiki/Reactive_programming
| 归档时间: |
|
| 查看次数: |
3791 次 |
| 最近记录: |