swift - 递归发送值到 combineLatest 发布者
问题描述
我在 Combine 中遇到了一些意想不到的行为,我希望有人能够解释。我希望下面的代码创建一个无限循环,但它实际上只在流中运行一次。
let pub1 = PassthroughSubject<Int, Never>()
let pub2 = PassthroughSubject<Int, Never>()
pub1
.handleEvents(receiveOutput: { print("Received new pub1 value: \($0)") })
.combineLatest(pub2)
.handleEvents(receiveOutput: { print("Received new combined value: \($0)") })
.sink { value in
print(value)
pub1.send(value.0)
}.store(in: &subscriptions)
print("sending 1")
pub1.send(1)
print("sending 2")
pub2.send(2)
生成以下输出:
Received new pub1 value: 1
sending 2
Received new combined value: (1, 2)
(1, 2)
Received new pub1 value: 1
由于 pub1 内部的值会反馈给自身,因此我希望 sink 会被一遍又一遍地调用。有趣的是,如果我去掉 combineLatest ,那么这段代码将创建一个无限循环。关于 combineLatest 运算符的某些东西正在阻止它,我不知道是什么。
我还注意到.receive(on: DispatchQueue.main)
在之前或之后添加combineLatest
也会触发循环。我想我不了解Combine中如何处理线程。我没有看到其他运营商的这种非循环行为。例如merge(with:)
,正如预期的那样,还将创建一个循环。
解决方案
推荐阅读
- python-3.x - 如何在beautifulsoup中分离td并获得第n个td?
- uitableview - 如何使用 diffable UITableView 更新表格单元格
- jmeter - 线程的 Beanshell 值不是随机的
- reactjs - 使用 Bootstrap 垂直对齐
- c++ - 如何在不视觉上使用滚动条的情况下更改视图
- java - java没有进入循环
- node.js - 带有 UnhandledPromiseRejectionWarning 的 Firebase 消息发送()错误
- css - CSS max-width 和 calc() 在这里真正做了什么?
- excel - 宏复制和粘贴并按前 3 个值(或更多)排序
- angular - 如何在 Angular 中更改内联 svg 的颜色?