RxSwift: Use Zip with different type observables

自作多情 提交于 2020-02-26 13:02:13

问题


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?


回答1:


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

zip(just(1), just("!")) { (a, b) in 
    return (a,b)
}



回答2:


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)
}


来源:https://stackoverflow.com/questions/34095592/rxswift-use-zip-with-different-type-observables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!