如何使用 combine Publisher 更改线程?

Posted

技术标签:

【中文标题】如何使用 combine Publisher 更改线程?【英文标题】:How to change thread using combine Publisher? 【发布时间】:2019-06-11 20:14:06 【问题描述】:

我正在使用 Combine 和 SwiftUI 来做一些异步的事情,关键是我不知道如何在主线程中接收来自异步操作的响应。 apple doc 表示它可以用于 RunLoop.main,但目前在 Swift 5.0 中它不是调度程序。那么对此有什么想法吗?

我尝试按照苹果文档使用,但没有运气。

anyPublisher
    .receiveOn(on: RunLoop.main)

【问题讨论】:

不确定您是否也遇到此问题,但是当我在 .subscribe(subscriber).sink(receiveValue: handler) 之前执行 receive(on: DispatchQueue.main) 时,他们没有收到输入。你遇到过吗? 【参考方案1】:

Combine - 在撰写本文时 - 尚未完全集成到 Foundation

根据 Xcode 11 Beta Release Notes:

Combine 框架的 Foundation 集成不可用。以下 Foundation 和 Grand Central Dispatch 与 Combine 的集成不可用:KeyValueObserving、NotificationCenter、RunLoop、OperationQueue、Timer、URLSession、DispatchQueue、JSONEncoder、JSONDecoder、PropertyListEncoder、PropertyListDecoder 和 @Published 属性包装器。 (51241500)


根据最新的 Xcode 11 beta (2),此问题已得到修复,因此希望您的代码能够正常工作。

Combine 框架的 Foundation 集成现已推出。以下 Foundation 和 Grand Central Dispatch 与 Combine 的集成可用:KeyValueObserving、NotificationCenter、RunLoop、OperationQueue、Timer、URLSession、DispatchQueue、JSONEncoder、JSONDecoder、PropertyListEncoder、PropertyListDecoder 和 @Published 属性包装器。 (51241500)

感谢@Martin R 和@silicon_valley 提供update。

【讨论】:

根据 Xcode 11 beta 2 发行说明,此问题已得到解决。 感谢@silicon_valley: ***.com/questions/56522258/… :)

以上是关于如何使用 combine Publisher 更改线程?的主要内容,如果未能解决你的问题,请参考以下文章

使用 combine's Publisher 在 SwiftUI Image 中从远程 URL 异步加载图像

使用 Swift Combine 创建一个 Timer Publisher

让自定义 Publisher 在 Swift Combine 上的不同 DispatchQueue 上运行

如何更改 Oracle BI Publisher 中的日期格式?

合并:将 Closure 转换为 Publisher

SwiftUI 结合 Publisher targetstruct 来解码数据