RxSwift 中 Observable 最后两个元素的运算符

Evg*_*eny 1 reactive-programming observable rx-swift reactive

我有一个可观察的Ints序列:

-1-2-3-4-5-6-3-4-5-1-
Run Code Online (Sandbox Code Playgroud)

例如,我需要检测前一个元素何时大于最后一个元素。

在这个序列中它是(6, 3)(5, 1)

-1-2-3-4-5-6-3-4-5-1-
-------------ˆ-----ˆ-
Run Code Online (Sandbox Code Playgroud)

在这种情况下我可以使用哪个运算符?

Man*_*ear 5

是的scan,您要找的接线员:

let stream = Observable<Int>.from([1, 2, 3, 4, 5, 6, 3, 4, 5, 1])
let seed = (0, 0) // (any Int, Int that smaller of all possible values of first emited Int)
let wrongPairs = stream
    .scan(seed) { last, new -> (Int, Int) in
        return (last.1, new)
    }
    .filter { $0.0 > $0.1 }
Run Code Online (Sandbox Code Playgroud)

随着scan我们地图的流Ints到流的Int对,然后筛选“良好”的所有对(前一个元素,如果小于或等于):

-1-2-3-4-5-6-3-4-5-1-
-(0, 1)-(1, 2)-(2, 3)-(3, 4)-(4, 5)-(5, 6)-(6, 3)-(3, 4)-(4, 5)-(5, 1)-
-(6, 3)-(5, 1)-
Run Code Online (Sandbox Code Playgroud)

缺点scan是你需要初始数字,这在某些情况下可能会出现问题,但如果你的流总是发出正数-1就可以了。