如何同時使用 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协议的正确使用场合(谨慎使用)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
虚拟现实:最后的传播
聂有兵 / 中国发展出版社 / 2017-4-1 / 39.00
本书对“虚拟现实”这一诞生自70年代却在今天成为热门话题的概念进行了历史发展式的分析和回顾,认为虚拟现实是当今最重大的社会变革的技术因素之一,对虚拟现实在未来百年可能给人类社会的各个层面带来的影响进行说明,结合多个大众媒介的发展趋势,合理地推演未来虚拟现实在政治、经济、文化等领域的态势,并基于传播学理论框架提出了几个新的观点。对于普通读者,本书可以普及一般的虚拟现实知识;对于传媒行业,本书可以引导......一起来看看 《虚拟现实:最后的传播》 这本书的介绍吧!