Rx scan(), cannot generate observable from seed an

2019-08-25 04:38发布

问题:

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