As we know, usually publishers are struct. What will change if it is a class?
Let's consider we have 1 publisher which emits 1 value and 2 subscribers, which subscribes to it.
let p1 = Just(20)
let s1 = p1.print().sink { _ in }
let s2 = p1.print().sink { _ in }
// s1 - receive value: (20)
// s2 - receive value: (20)
in print logs, we can see that both subscribers got value (20).
If we open the documentation of share() operator, we will see
share() - Returns a publisher as a class instance.
So it just changes semantic of the publisher from value to reference. In our example, we don't pass p1
publisher to any function or assign to any object and that's why for me there is no difference publisher is struct or class ...
But if I add share()
operator behavior will be different, s2
won't get value.
let p1 = Just(20).share() // !
let s1 = p1.print().sink { _ in }
let s2 = p1.print().sink { _ in }
// s1 - receive value: (20)
I saw some examples with URLSession.shared.dataTaskPublisher(\_: URL)
or with some "delayed" publishers, when s2
also gets value, but it's still unclear for me how just changing semantic of publisher change its behaviour in such way.