如何使用RxJs distinctUntilChanged? [英] How to use RxJs distinctUntilChanged?
问题描述
我开始使用RxJs(使用v5测试版),但不知何故我无法弄清楚如何使用 distinctUntilChanged
。如果我在babel-node中运行它,下面代码的输出是
I'm getting started with RxJs (using the v5 beta), but somehow I can't figure out how to work with distinctUntilChanged
. The output from the code below if I run it in babel-node is
[ 'a', 1 ]
{ key: 'a', state: 1 }
Next: { value: 42 }
Completed
这不是我所期望的。为什么只有一个条目通过 distinctUntilChanged
?我希望输出为
That is not what I would expect. Why is only one entry passing distinctUntilChanged
? I would expect the output to be
[ 'a', 1 ]
[ 'a', 0 ]
[ 'a', 1 ]
{ key: 'a', state: 1 }
{ key: 'a', state: 2 }
{ key: 'a', state: 0 }
{ key: 'a', state: 1 }
Next: { value: 42 }
Next: { value: 24 }
Completed
这是代码
import {Observable} from 'rxjs'
Observable.of(['a', 1], ['a', 1], ['a', 0], ['a', 1])
.distinctUntilChanged(x => x[1])
.subscribe(x => console.log(x))
Observable.of({key: 'a', state: 1}, {key: 'a', state: 2}, {key: 'a', state: 0}, {key: 'a', state: 1})
.distinctUntilChanged(x => x.state)
.subscribe(x => console.log(x))
Observable.of({value: 42}, {value: 42}, {value: 24}, {value: 24})
.distinctUntilChanged(x => x.value)
.subscribe(
function (x) {
console.log('Next: ', x)
},
function (err) {
console.log('Error: ' + err)
},
function () {
console.log('Completed')
}
)
这些功能的v5文档中的链接似乎是死了
The links in the v5 docs for these functions appear to be dead
------编辑-----
------ edit -----
一些额外的调试:
Observable.of(['a', 1], ['a', 1], ['a', 0], ['a', 1])
.do(x => console.log('before', x))
.distinctUntilChanged(x => x[1])
.do(x => console.log('after', x))
.subscribe(x => console.log(x))
输出:
before [ 'a', 1 ]
after [ 'a', 1 ]
[ 'a', 1 ]
before [ 'a', 1 ]
before [ 'a', 0 ]
before [ 'a', 1 ]
推荐答案
我得到了答案此处。基本上函数签名从(键选择器,比较器)变为(比较器,键选择器)。
I got an answer here. Basically the function signature changed from (key selector, comparator) to (comparator, key selector).
这是在v5中完成示例的方式:
This is how the example is done in v5:
Observable.of(['a', 1], ['a', 1], ['a', 0], ['a', 1])
.distinctUntilChanged(null, x => x[1])
.subscribe(x => console.log(x))
这篇关于如何使用RxJs distinctUntilChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!