如何同時使用 RxJS 與 Ramda ?
栏目: JavaScript · 发布时间: 6年前
内容简介:RxJS 與 Ramda 同屬 Functional Library,RxJS 特色在於 Asynchronous 部分,而 Ramda 則在於 Synchronous 部分,事實上 RxJS 與 Ramda 可以搭配一起在 Vue 使用。Vue 2.6.6Vue-rx 6.1.0
RxJS 與 Ramda 同屬 Functional Library,RxJS 特色在於 Asynchronous 部分,而 Ramda 則在於 Synchronous 部分,事實上 RxJS 與 Ramda 可以搭配一起在 Vue 使用。
Version
Vue 2.6.6
Vue-rx 6.1.0
RxJS 6.4.0
Ramda 0.26.1
RxJS
<template>
<div>
<h1>{{ interval1$ }}</h1>
<h1>{{ interval2$ }}</h1>
</div>
</template>
<script>
import { interval } from 'rxjs'
import { map } from 'rxjs/operators'
const interval$ = interval(1000)
const interval1$ = interval$.pipe(map(x => x * 2))
const interval2$ = interval$.pipe(map(x => x * 3))
export default {
name: 'app',
subscriptions: () => ({
interval1$,
interval2$
})
}
</script>
18 行
subscriptions: () => ({
interval1$,
interval2$
})
subscriptions
如 data
一樣,本質是 function,將所有的 Observable 宣告在 subscriptions()
的 return object。
const interval$ = interval(1000) const interval1$ = interval$.pipe(map(x => x * 2)) const interval2$ = interval$.pipe(map(x => x * 3))
定義 interval$
Observable,由於並不需要顯示在 HTML Template 內,因此不需要定義在 subscriptions
內。
實務上並不需要所有 Observable 都宣告在 subscriptions
內,只有需要做 Data Binding 的 Observable 才要在 subscriptions
內宣告
以 interval$
定義 interval1$
與 interval2$
,使用 RxJS 的 map()
operator 重新定義 Observable。
RxJS 如同 Ramda 一樣,其 operator 要包在 pipe()
內。
目前為止一切順利,唯 map()
的 callback 並非 Point-free,有辦法繼續改善嗎 ?
Ramda
<template>
<div>
<h1>{{ interval1$ }}</h1>
<h1>{{ interval2$ }}</h1>
</div>
</template>
<script>
import { interval } from 'rxjs'
import { map } from 'rxjs/operators'
import { multiply } from 'ramda'
const interval$ = interval(1000)
const interval1$ = interval$.pipe(map(multiply(2)))
const interval2$ = interval$.pipe(map(multiply(3)))
export default {
name: 'app',
subscriptions: () => ({
interval1$,
interval2$
})
}
</script>
13 行
const interval$ = interval(1000) const interval1$ = interval$.pipe(map(multiply(2))) const interval2$ = interval$.pipe(map(multiply(3)))
引進了 Ramda 的 multiply()
operator,如此 map() 也 Point-free 了。
Conclusion
- RxJS 與 Ramda 雖然分屬兩個不同的 library,但彼此可以相互搭配,使 RxJS 也能 Point-free
-
由於 Vue 的
computed、method、subscriptions本質都是 function,因此可以使用 RxJS 與 Ramda 產生,充分發揮 FP 的 Function Composition
Sample Code
完整範例可以在我 GitHub 上找到
以上所述就是小编给大家介绍的《如何同時使用 RxJS 與 Ramda ?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- RecyclerView使用指南(一)—— 基本使用
- 如何使用Meteorjs使用URL参数
- 使用 defer 还是不使用 defer?
- 使用 Typescript 加强 Vuex 使用体验
- [译] 何时使用 Rust?何时使用 Go?
- UDP协议的正确使用场合(谨慎使用)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
系统分析与设计方法
惠滕 / 孙慧、肖刚 / 机械工业出版社 / 2004-9 / 69.00元
本书是介绍信息系统分析和设计原理、方法、技术、工具和应用的力作,自问世以来,广受欢迎,以至于一版再版,延续至今。 本书采用一个完整的案例研究,以整个信息系统构件(基于Zachman框架)和信息系统开发生命周期(FAST方法学)为主线,详细探讨了系统开发生命周期的前期、中期和后期以及跨生命周期的活动。另外,书中第一章都提供了大量的练习题、讨论题、研究题和小型案例,以加深读者对书中所述理论的实际应用和......一起来看看 《系统分析与设计方法》 这本书的介绍吧!