hopy
hopy

Reputation: 615

Why String.publisher can't be triggered?

I execute my code in Playground:

import PlaygroundSupport
import Combine

PlaygroundPage.current.needsIndefiniteExecution = true

var s = "a"
let sb = s.publisher
    .sink(receiveValue: {
        print("rec: \($0)")
    })

let s0 = Timer.publish(every: 1.0, on: .main, in: .common)
.autoconnect()
.sink(receiveValue: {_ in
    print("tiktok...")
    s.append("not work!")
})
s.append("not work too!")

My Question is why s.publisher can't be triggered even though I changed s value???

Upvotes: 0

Views: 65

Answers (2)

David Pasztor
David Pasztor

Reputation: 54716

The issue is that Array.Publisher simply emits all elements of the array and then completes. It doesn't wait for mutations of the array.

If you want to emit a value every time a String changes its value, you need to store that String in a class as @Published and subscribe to the publisher of the Published property.

class StringPublisher: ObservableObject {
    @Published var value: String

    init(value: String) {
        self.value = value
    }
}

let s = StringPublisher(value: "a")
let sb = s.$value.sink(receiveValue: {
    print("rec: \($0)")
})

let s0 = Timer.publish(every: 1.0, on: .main, in: .common)
.autoconnect()
.sink(receiveValue: {_ in
    print("tiktok...")
    s.value.append("now work!")
})

s.value.append("now work too!")

Upvotes: 2

Dmitriy Lupych
Dmitriy Lupych

Reputation: 639

Your sb publisher emits all its values and successfully completes. That's why after appending chars to your initial string, it doesn't trigger publishing events

Upvotes: 0

Related Questions