ios - 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()
解决方案
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()
推荐阅读
- c# - 具有长后台进程和 UI 更新的 ASP.NET Core
- ios - 如何使用 Swift 和 PDFKit 在交互式 pdf 文件中使用自定义文本完成注释?
- text-to-speech - TTS API 中本地语音合成器的含义是什么
- android - 如何使用一个按钮来获取文本并将文本设置为 3 个不同的 EditTexts 和 TextViews
- javascript - Google API:表格图表中列单元格的闪烁背景颜色
- javascript - javascript中的构造函数中的对象文字和具有值的类之间有什么区别?
- php - 如何在 postRemove 事件期间获取实体的对象 ID?
- c# - 有没有办法将复杂类型映射到字符串?
- kendo-ui - Kendo UI 组件是否可免费用于 Excel 导入/导出?
- c# - 创建对象的唯一 HashSet