有没有一种方法可以在Swift Combine中多次调用assign()?

时间:2020-03-30 16:19:35

标签: swift combine observableobject

我想用处理新发布的值时收到的值来更新一些变量。例如,给定:

class ProductViewModel: ObservableObject {
    @Published var PublishedX: Int = 0
    @Published var PublishedY: Int = 0
    @Published var PublishedProduct: Int = 0
    // ...
    init() {
        productPublisher = Publishers.CombineLatest(external.XPublisher, internal.YPublisher)
            // .assignAndContinue(\.PublishedX, \.PublishedY) // something like this
            .flatMap(MyPublishers.secretMultiplication)
            .assign(to: \.PublishedProduct, on: self)
     }
 }

我还希望将XPublisher和YPublisher的新值分配给变量(分别为PublisheredX和PublishedY)。

是否可以设置这两个变量,然后继续处理事件?

2 个答案:

答案 0 :(得分:0)

没有assign(to:on:)的内置变体返回另一个Publisher而不是Cancellable

只需使用多个assign

class ProductViewModel: ObservableObject {
    @Published var PublishedX: Int = 0
    @Published var PublishedY: Int = 0
    @Published var PublishedProduct: Int = 0

    init() {
        external.XPublisher
            .assign(to: \.PublishedX, on: self)
            .store(in: &tickets)
        internal.YPublisher
            .assign(to: \.PublishedY, on: self)
            .store(in: &tickets)
        external.XPublisher
            .combineLatest(internal.YPublisher) { $0 * $1 }
            .assign(to: \.PublishedProduct, on: self)
            .store(in: &tickets)
    }

    private var tickets: [AnyCancellable] = []
}

请注意,这些订阅会创建保留周期。在清除ProductViewModel数组之前,Swift将无法销毁tickets的实例。 (这不是我的建议的属性。您的原始代码也需要将其订阅存储在某个地方,否则它将立即被取消。)

此外,PublishedProduct是否存在令人怀疑。为什么不只是计算属性?

var product: Int { PublishedX * PublishedY }

答案 1 :(得分:0)

您可能想check out this library

来自他们的ReadMe

var label1: UILabel
var label2: UILabel
var text: UITextField

["hey", "there", "friend"]
    .publisher
    .assign(to: \.text, on: label1,
            and: \.text, on: label2,
            and: \.text, on: text)