Rx scan(), cannot generate observable from seed and another observable

大兔子大兔子 提交于 2019-12-11 14:14:32

问题


I have a seed value Triangle (Bool) and an observable that emits values Circle (Int). My intention is to generate a new observable (Triangle, Circle) each time a value is emitted from that observable, transforming the Triangle value negating the current value. This is my marble diagram:

But I cannot achieve it, and I don't know if scan is the correct operator. This is my code:

typealias Triangle = Bool
typealias Circle = Int

func scan() {
    let triangle: Triangle = false
    circleObservable
        .scan(triangle, accumulator: ({ (triangle, circle) -> (Triangle, Circle) in
            return (!triangle, circle)
        }))
}

This generates a compiler error:

Cannot convert value of type '(Triangle, Circle) -> (Triangle, Circle)' (aka '(Bool, Int) -> (Bool, Int)') to expected argument type '(_, _) -> _'

Thanks!


回答1:


circleObservable.scan((Triangle(false), Circle()), accumulator: { lastValue, circle -> (Triangle, Circle) in (!lastValue.0, circle) })

Or simpler:

typealias Triangle = Bool
typealias Circle = Int

func scan(circle: Observable<Circle>) -> Observable<(Triangle, Circle)> {
    return circle.scan((Triangle(false), Circle())) { (!$0.0, $1) }
}



回答2:


Perhaps 'throws' is missing? Have a look at this working example - https://github.com/maxvol/RaspSwift/blob/master/RaspSwift/RaspAggregator.swift



来源:https://stackoverflow.com/questions/47305554/rx-scan-cannot-generate-observable-from-seed-and-another-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!