Is this a normal behavior about Publisher.Share

from this link https://developer.apple.com/documentation/combine/publishers/merge/share()

let pub = (1...3).publisher
.delay(for: 1, scheduler: DispatchQueue.main)
.map( { _ in return Int.random(in: 0...100) } )
.print("Random")
.share()

cancellable1 = pub
.sink { print ("Stream 1 received: \($0)")}
cancellable2 = pub
.sink { print ("Stream 2 received: \($0)")}

// Prints:
// Random: receive value: (20)
// Stream 1 received: 20
// Stream 2 received: 20
// Random: receive value: (85)
// Stream 1 received: 85
// Stream 2 received: 85
// Random: receive value: (98)
// Stream 1 received: 98
// Stream 2 received: 98

but if I do like this below, share doesn't work as I expected

var pub: Publishers.Share<AnyPublisher<Int, Never>> {
    (1...3).publisher
        .delay(for: 1, scheduler: DispatchQueue.main)
        .map( { _ in return Int.random(in: 0...100) } )
        .print("Random")
        .eraseToAnyPublisher()
        .share()
}
cancellable1 = pub
.sink { print ("Stream 1 received: \($0)")}
cancellable2 = pub
.sink { print ("Stream 2 received: \($0)")}

// Prints:    
// Random: receive value: (99)
// Stream 1 received: 99
// Random: receive value: (56)
// Stream 1 received: 56
// Random: receive value: (38)
// Stream 1 received: 38
// Random: receive finished
// Random: receive value: (98)
// Stream 2 received: 98
// Random: receive value: (11)
// Stream 2 received: 11
// Random: receive value: (32)
// Stream 2 received: 32

What's the difference between these?

Terms of Service

Privacy Policy

Cookie Policy