-
Notifications
You must be signed in to change notification settings - Fork 2
/
transformations.js
42 lines (38 loc) · 1.14 KB
/
transformations.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import {LiveData} from './livedata.js'
export function map(livedata, transformer) {
let unsubscribe
const mapped = new LiveData(
transformer(livedata.get()), // Initial value is mapped from original current value
() => {
// When becoming active add to subscribers of original LiveData
unsubscribe = livedata.subscribe(v => mapped.set(transformer(v)))
},
() => {
// When becoming inactive remove from subscribers of original LiveData
unsubscribe()
})
return mapped
}
export function switchMap(livedata, transformer) {
let unsubscribe
let currentResult
let resultUnsubscribe
const switched = new LiveData(
transformer(livedata.get()).get(),
() => {
unsubscribe = livedata.subscribe(v => {
const newResult = transformer(v)
if (currentResult !== newResult) {
resultUnsubscribe && resultUnsubscribe()// eslint-disable-line no-unused-expressions
currentResult = newResult
resultUnsubscribe = newResult.subscribe(v => switched.set(v))
}
})
},
() => {
resultUnsubscribe()
unsubscribe()
}
)
return switched
}