RxSwift:将 Zip 与不同类型的可观察对象结合使用 [英] RxSwift: Use Zip with different type observables

查看:104
本文介绍了RxSwift:将 Zip 与不同类型的可观察对象结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 RxSwift 2.0.0-beta

I'm using RxSwift 2.0.0-beta

如何以类似 zip 的方式组合 2 个不同类型的 observable?

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?

推荐答案

这对我有用.我在 Xcode7 中测试过,RxSwift-2.0.0-beta

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

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

这篇关于RxSwift:将 Zip 与不同类型的可观察对象结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆