首页 > 解决方案 > Swift Combine按顺序制作序列

问题描述

这是一个简单的游乐场代码,它以相反的顺序显示两个订阅。如何修改代码使其始终打印出 555?目前它随机打印 0 或 555,因为操作是异步的。请记住,这是一个概念,而不是要解决的实际问题,因此将所有东西放在一个水槽中并不是解决方案。谢谢

import Combine

class Foo {

    let subject = PassthroughSubject<Void, Never>()
    var myProperty = 0

    var bag = Set<AnyCancellable>()

    init() {
        subject
            .sink { _ in print(self.myProperty) }
            .store(in: &bag)

        subject
            .map { _ in 555 }
            .assign(to: \.myProperty, on: self)
            .store(in: &bag)

        subject.send()
    }
}

let testClass = Foo()

标签: iosswiftqueuecombine

解决方案


PassthroughSubject不保证向订阅者发送值的顺序。您不能强制执行订单,并且该订单可能会在未来版本的 Combine 中更改。

一种存储myProperty在其自己的主题中并订阅该主题以获得 +555 值的解决方案:

import Combine

class Foo {
    
    let subject = PassthroughSubject<Void, Never>()
    private var _myProperty = CurrentValueSubject<Int, Never>(0)
    var myProperty: Int { _myProperty.value }
    
    var bag = Set<AnyCancellable>()
    
    init() {
        _myProperty
            .sink { _ in print(self.myProperty) }
            .store(in: &bag)
        
        subject
            .map { _ in 555 }
            .assign(to: \.value, on: _myProperty)
            .store(in: &bag)
        
        subject.send()
    }
}

let testClass = Foo()

推荐阅读