RxSwift: Use Zip with different type observables

2020-06-12 02:47发布

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?

3条回答
该账号已被封号
2楼-- · 2020-06-12 03:06

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

zip(just(1), just("!")) { (a, b) in 
    return (a,b)
}
查看更多
干净又极端
3楼-- · 2020-06-12 03:13

If you using Singles (RxSwift 5.0+)

Single.zip(single1, single2) {
    return ($0, $1)
}

or

Observable.zip(single1.asObservable(), single2.asObservable()) {
    return ($0, $1)
}

Example:

let task = Single
                .zip(repository.getArrayA(), repository.getArrayB())
                { (a: [A], b: [B]) in
                    return (a, b)
                }                    
                .do(onSuccess: { (zip) in
                let (a, b) = zip

                // your code

                //example: self.updateSomething(a, b)

            })
            .asCompletable()
查看更多
Evening l夕情丶
4楼-- · 2020-06-12 03:24

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)
}
查看更多
登录 后发表回答