如何同時使用 RxJS 與 Ramda ?

栏目: JavaScript · 发布时间: 7年前

内容简介: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$
})

subscriptionsdata 一樣,本質是 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 的 computedmethodsubscriptions 本質都是 function,因此可以使用 RxJS 與 Ramda 產生,充分發揮 FP 的 Function Composition

Sample Code

完整範例可以在我 GitHub 上找到


以上所述就是小编给大家介绍的《如何同時使用 RxJS 與 Ramda ?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计算机图形学

计算机图形学

[美]PeterShirley / 高春晓、赵清杰、张文耀 / 人民邮电出版社 / 2007-6 / 49.00元

本书是国外高校采用率很高的计算机图形学教材,共分为26章,全面系统地讲解了计算机图形学的基本概念和相关技术。书中先介绍图形学相关的数学知识,然后依次讲解图形学的光栅算法、三三维观察、隐藏面消除、光照、纹理、绘制等算法和理论,并介绍可视感知、计算机动画、基于图像的绘制、可视化以及构建交互式图形应用等。 本书可作为信息技术等相关专业本科生、研究生计算机图形学课程的教材,也可以作为计算机图形学工作......一起来看看 《计算机图形学》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

MD5 加密
MD5 加密

MD5 加密工具