I'm experiencing this really weird issue/bug with SwiftUI. In the setupSubscription method, I'm creating a subscription to subject and inserting it into the cancellables Set. And yet, when I print the count of cancellables, I get zero. How can the set be empty if I just inserted an element into it?
This is presumably why the handleValue method is not called when I tap on the button. Here's the full output from the console:
init
begin setupSubscription
setupSubscription subject sink: receive subscription: (CurrentValueSubject)
setupSubscription subject sink: request unlimited
setupSubscription subject sink: receive value: (initial value)
handleValue: 'initial value'
setupSubscription: cancellables.count: 0
setupSubscription subject sink: receive cancel
sent value: 'value 38'
cancellables.count: 0
sent value: 'value 73'
cancellables.count: 0
sent value: 'value 30'
cancellables.count: 0
What am I doing wrong? why Is my subscription to subject getting cancelled? Why is handleValue not getting called when I tap the button?
import SwiftUI
import Combine
struct Test: View {
@State private var cancellables: Set<AnyCancellable> = []
let subject = CurrentValueSubject<String, Never>("initial value")
init() {
print("init")
self.setupSubscription()
}
var body: some View {
VStack {
Button(action: {
let newValue = "value \(Int.random(in: 0...100))"
self.subject.send(newValue)
print("sent value: '\(newValue)'")
print("cancellables.count:", cancellables.count)
}, label: {
Text("Tap Me")
})
}
}
func setupSubscription() {
print("begin setupSubscription")
let cancellable = self.subject
.print("setupSubscription subject sink")
.sink(receiveValue: handleValue(_:))
self.cancellables.insert(cancellable)
print("setupSubscription: cancellables.count:", cancellables.count)
// prints "setupSubscription: cancellables.count: 0"
}
func handleValue(_ value: String) {
print("handleValue: '\(value)'")
}
}