Skip to content

Instantly share code, notes, and snippets.

@Marcocanc
Last active November 19, 2019 14:17
Show Gist options
  • Save Marcocanc/44aa05c3e3566af63e84c126af58b704 to your computer and use it in GitHub Desktop.
Save Marcocanc/44aa05c3e3566af63e84c126af58b704 to your computer and use it in GitHub Desktop.
extension SignalProducer {
func replayingShare() -> SignalProducer<Value, Error> {
let subCount = Atomic<UInt64>(0)
var upstreamLifetime = Lifetime.empty
var token = Lifetime.Token()
var replayedProducer: SignalProducer<Value, Error> = .empty
return SignalProducer { observer, lifetime in
if upstreamLifetime.hasEnded {
upstreamLifetime = Lifetime(token)
replayedProducer = self
.take(during: upstreamLifetime)
.replayLazily(upTo: 1)
}
lifetime.observeEnded {
var dispose = false
subCount.modify {
$0 -= 1
if $0 < 1 {
dispose = true
}
}
if dispose {
// Overwrite the previous token with a new one.
// This causes the Lifetime associated with that Token to end.
token = Lifetime.Token()
}
}
subCount.modify { $0 += 1 }
lifetime += replayedProducer.start(observer)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment