【问题标题】:How to FlatMap a Publisher of two Tuples into a Publisher with one Tuple如何将两个元组的发布者平面映射到一个元组的发布者中
【发布时间】:2021-06-20 16:55:44
【问题描述】:

我有以下代码

 private var codeState : AnyPublisher<((Bool,Bool,Bool,Bool),(Bool,Bool)), Never> {
    let publ1 =  Publishers.CombineLatest4(firstCodeAnyPublisher,secondCodeAnyPublisher,thirdCodeAnyPublisher,fourthCodeAnyPublisher)
    let pub2 = Publishers.CombineLatest(fifthCodeAnyPublisher, sixthCodeAnyPublisher)
    return publ1.combineLatest(pub2)
        .eraseToAnyPublisher()
}

此操作生成具有两个布尔元组的任何发布者 如何将它们转换为具有以下一个元组的发布者

AnyPublisher<(Bool,Bool,Bool,Bool,Bool,Bool), Never>

【问题讨论】:

    标签: ios tuples combine publisher


    【解决方案1】:

    我不得不说发布一个包含两个未命名Bools 或四个未命名Bools 或六个未命名Bools 的元组可能是个坏主意。您至少应该标记这些值,并且可能应该创建 structs 而不是使用元组。

    也就是说,您可以申请the map operator 来合并元组:

    private var codeState : AnyPublisher<(Bool,Bool,Bool,Bool,Bool,Bool), Never> {
        let publ1 =  Publishers.CombineLatest4(firstCodeAnyPublisher,secondCodeAnyPublisher,thirdCodeAnyPublisher,fourthCodeAnyPublisher)
        let pub2 = Publishers.CombineLatest(fifthCodeAnyPublisher, sixthCodeAnyPublisher)
        return publ1.combineLatest(pub2)
            .map { ($0.0, $0.1, $0.2, $0.3, $1.0, $1.1) }
            .eraseToAnyPublisher()
    }
    

    其实combineLatest has an overload就是把transform函数作为一个额外的参数,为你应用map,所以也可以这样写:

    private var codeState : AnyPublisher<(Bool,Bool,Bool,Bool,Bool,Bool), Never> {
        let publ1 =  Publishers.CombineLatest4(firstCodeAnyPublisher,secondCodeAnyPublisher,thirdCodeAnyPublisher,fourthCodeAnyPublisher)
        let pub2 = Publishers.CombineLatest(fifthCodeAnyPublisher, sixthCodeAnyPublisher)
        return publ1.combineLatest(pub2) {
            ($0.0, $0.1, $0.2, $0.3, $1.0, $1.1)
        }
        .eraseToAnyPublisher()
    }
    

    您应该使用您认为更容易理解的版本。没有一个比另一个更有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 2021-08-21
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多