Swift 组合:合并多个发布者,并在其中任何一个发布者发出“true”时发出“true”

2024-04-10

我正在尝试构建一个当其他 5 个发布者中的任何一个发出 true 时发出 true 的发布者。我已经成功构建了一个工作版本,但感觉非常恶心,使用CombineLatest4+CombineLatest,尤其是所有$0.0 || $0.1 || $0.2 || $0.3 code.

我尝试过 Merge5,但它只是返回看起来设置的最后一个值的值。

import Foundation
import Combine

class Test {
  @Published var one = false
  @Published var two = false
  @Published var three = false
  @Published var four = false
  @Published var five = false
}

let test = Test()

var anyTrue = Publishers.CombineLatest4(test.$one, test.$two, test.$three, test.$four)
  .map { $0.0 || $0.1 || $0.2 || $0.3 }
  .combineLatest(test.$five)
  .map { $0.0 || $0.1 }

anyTrue.sink {
  print($0)
}

test.three = true
test.one = false

有没有一种更干净、更少重复的方法来做到这一点?


我写了这个自定义变量combineLatest结合了N个发布者的函数。希望这是您所需要的:

func combineLatestN<P, T, E>(identity: T, reductionFunction: @escaping (T, T) -> T, publishers: P...) -> AnyPublisher<T, E> 
    where P: Publisher, P.Output == T, P.Failure == E {
    publishers.reduce(
        Publishers.Sequence<[T], E>(sequence: [identity]).eraseToAnyPublisher(), 
        { $0.combineLatest($1).map(reductionFunction).eraseToAnyPublisher() }
    )
}

困难的部分是弄清楚这个人的身份reduce应该。什么出版社x满足x.combineLatest(y).map(f) == y对全部y?一种解决方案x将是一个发布身份的发布者f once.

Usage:

let anyTrue = combineLatestN(
                identity: false, 
                reductionFunction: { $0 || $1 }, 
                publishers: test.$one, test.$two, test.$three, test.$four, test.$five)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift 组合:合并多个发布者,并在其中任何一个发布者发出“true”时发出“true” 的相关文章

随机推荐