如何使用组合观察数组的新值?



如果我有一个数组:

var arr = [0,1,2]

联合出版商:

arr.publisher
.sink { completion in print("Completed with (completion)")
} receiveValue: { val in
print("Received value (val)")
}
arr.append(3)

为什么它立即结束:

Received value 0
Received value 1
Received value 2
Completed with finished

如何使Combine每次向数组追加值时都执行代码?

数组的publisher方法正是这样做的——发出数组的每个元素,然后完成,因为在调用发布者时数组的元素数量有限。

如果您希望在每次阵列更改时(不仅是在向其添加内容时,而且在任何更改时(都得到通知,则为阵列创建一个@Published var,并将观察器附加到它上:

@Published var arr = [1,2,3]
cancellable = $arr
.sink { completion in print("Completed with (completion)")
} receiveValue: { val in
print("Received value (val)")
}
arr.append(4)

输出为:

Received value [1, 2, 3]
Received value [1, 2, 3, 4]

但看起来你真正想要的是一次听一个数字流。然后定义一个该类型的@Published var并监听它

@Published var value = 1
cancellable = $value
.sink { completion in print("Completed with (completion)")
} receiveValue: { val in
print("Received value (val)")
}
value = 2
value = 3
value = 4

输出为:

Received value 1
Received value 2
Received value 3
Received value 4

相关内容

  • 没有找到相关文章

最新更新