如何将两个元组的发布者平面映射为一个元组的发布者

How to FlatMap a Publisher of two Tuples into a Publisher with one Tuple

我有以下代码

 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>

我不得不说发布一个包含两个未命名 Bool 或四个未命名 Bool 或六个未命名 Bool 的元组可能不是一个好主意。您至少应该标记值,也许您应该创建 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 { ([=10=].0, [=10=].1, [=10=].2, [=10=].3, .0, .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) {
        ([=11=].0, [=11=].1, [=11=].2, [=11=].3, .0, .1)
    }
    .eraseToAnyPublisher()
}

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