如何用 combine 观察数组的新值?
How to observe array's new values with combine?
如果我有一个数组:
var arr = [0,1,2]
以及它的 Combine 发布者:
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
,听听。每次 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
如果我有一个数组:
var arr = [0,1,2]
以及它的 Combine 发布者:
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
,听听。每次 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