Search code examples
swiftfunctional-programmingreactive-swift

Adding a stream of numbers using ReactiveSwift


New at ReactiveSwift and FRP in general, trying to build a small calculator app to try to get the hang of it and I'm stuck figuring out the reactive way to do something like this. If I have a function that takes a value, how do I pass that value to a stream that is constantly applying a function that takes the value passed, and the result of all the previous values? For example, how would I add up a stream of integers? Sample code would be super helpful. Something like this

func apply(_ value: Int) {
 /// sends value to a stream that emits (value + previous values) to its observers
}

Solution

  • You probably want to take a look at the scan operator, which lets you specify an initial value and a function for accumulating new values. I haven't verified this code, but it'll be something like this:

    let (signal, observer) = Signal<Int, NoError>.pipe()
    
    signal
        .scan(0) { acc, val in acc + val }
        .observeValues { val in print(val) }
    
    observer.send(value: 15) // Should print 15
    observer.send(value: 6) // Should print 21
    observer.send(value: 3) // Should print 24
    

    You could wrap it in a class like this (again, haven't tested this but it should get the idea across):

    class Adder {
        public let output: Signal<Int, NoError>
    
        private let input: Observer<Int, NoError>
    
        init() {
            let (signal, observer) = Signal<Int, NoError>.pipe()
    
            self.input = observer
    
            self.output = signal
                .scan(0) { acc, val in acc + val }
        }
    
        func apply(_ value: Int) {
            input.send(value: value)
        }
    }