Search code examples
swiftreactive-cocoareactive-swift

How to combine three Signals using reactive cocoa in swift?


I have read the documentation, it looks like "and" isn't suitable to combine signals. Then, I have looked into "combineLatest" but it expects atleast one value is returned from each signal. My use case, is I have three separate signals, they have no relation among them. I just want to combine them altogether and observe in one place and handle accordingly inside the closure.

For example:

Signal1<Int, NoError>
Signal2<String, NoError>
Signal3<SomeType, NoError>

Combine3Signals<(Int, String, SomeType), NoError>.observeValues {...//handle accordingly based on type...}

Solution

  • You can use Signal.merge for that, but first you have to convince the Compiler that you actually want to merge those different types

    let p1 = MutableProperty<Int>(1)
    let p2 = MutableProperty<Bool>(false)
    let p3 = MutableProperty<String>("")
    
    let s1: Signal<Any, NoError> = p1.signal.map { $0 }
    let s2: Signal<Any, NoError> = p2.signal.map { $0 }
    let s3: Signal<Any, NoError> = p3.signal.map { $0 }
    
    let merged = Signal<Any, NoError>.merge(s1, s2, s3)
    merged.observeValues { print($0) }
    
    
    p1.value = 2
    p1.value = 3
    p3.value = "Hello"
    p2.value = true
    

    Without the map, the compiler will complain

    error: cannot convert value of type 'Signal<Int, NoError>' to specified type 'Signal<Any, NoError>'