I've always thought .share(replay: 1, scope: .forever) shares the single upstream subscription no matter how many downstream subscribers there are.
However, I've just discovered that if the count of the downstream subscriptions drops to zero, it stops "sharing" and releases the subscription on the upstream (because refCount() is used under the hood). So when a new downstream subscription happens, it has to re-subscribe on the upstream. In the following example:
let sut = Observable<Int>
.create { promise in
print("create")
promise.onNext(0)
return Disposables.create()
}
.share(replay: 1, scope: .forever)
sut.subscribe().dispose()
sut.subscribe().dispose()
I would expect create to be printed just once, but it gets printed twice. And if I remove .dispose() calls - just once.
How do I set up the chain where the upstream is guaranteed to be subscribed at most once?