Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift: Use Zip with different type observables

Tags:

swift

rx-swift

I'm using RxSwift 2.0.0-beta

How can I combine 2 observables of different types in a zip like manner?

// This works
[just(1), just(1)].zip { intElements in
    return intElements.count
}

// This doesn't
[just(1), just("one")].zip { differentTypeElements in 
    return differentTypeElements.count
}

The current workaround I have is to map everything to an optional tuple that combines the types, then zips optional tuples into a non-optional one.

    let intObs = just(1)
        .map { int -> (int: Int?, string: String?) in
            return (int: int, string: nil)
    }
    let stringObs = just("string")
        .map { string -> (int: Int?, string: String?) in
        return (int: nil, string: string)
    }
    [intObs, stringObs].zip { (optionalPairs) -> (int: Int, string: String) in
        return (int: optionalPairs[0].int!, string: optionalPairs[1].string!)
    }

That's clearly pretty ugly though. What is the better way?

like image 651
GDanger Avatar asked Dec 04 '15 19:12

GDanger


People also ask

What is combineLatest in RxSwift?

.combineLatest() Combine the latest values from each supplied Observable using a supplied function. Both Observables need to emit an element for combining to happen. Operator receives a closure predicate that is applied to each emitted element. The latest elements from each Observable are combined.

What is observable zip?

The Zip method returns an Observable that applies a function of your choosing to the combination of items emitted, in sequence, by two (or more) other Observables, with the results of this function becoming the items emitted by the returned Observable.

What is onNext in RxSwift?

- parameter onNext: Action to invoke for each element in the observable sequence. - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. - parameter onError: Action to invoke upon errored termination of the observable sequence.

What is observable RxSwift?

The heart of the RxSwift framework is based on observable which is also known as a sequence. Observable is the sequence of data or events which can be subscribed and can be extended by applying different Rx operators like map, filter, flatMap, etc. It can receive data asynchronously.


2 Answers

Here is how to make it work for RxSwift 2.3+

Observable.zip(Observable.just(1), Observable.just("!")) {
    return ($0, $1)
}

or

Observable.zip(Observable.just(1), Observable.just("!")) {
    return (anyName0: $0, anyName1: $1)
}
like image 110
Jibeex Avatar answered Sep 22 '22 18:09

Jibeex


This works for me. I tested it in Xcode7, RxSwift-2.0.0-beta

zip(just(1), just("!")) { (a, b) in 
    return (a,b)
}
like image 39
Wonjung Kim Avatar answered Sep 21 '22 18:09

Wonjung Kim