Skip to content

Instantly share code, notes, and snippets.

@huwr
Created August 26, 2021 04:51
Show Gist options
  • Save huwr/4489f7caa2a4f35a07756910838da7d2 to your computer and use it in GitHub Desktop.
Save huwr/4489f7caa2a4f35a07756910838da7d2 to your computer and use it in GitHub Desktop.
Combine Publisher share replace once
public extension Publisher {
/// A variation on [share()](https://developer.apple.com/documentation/combine/publisher/3204754-share)
/// that allows for buffering and replaying a single event to future subscribers.
///
/// - Parameter initialValue: The initial value of the buffer, if none has been emitted before.
/// - Returns: A publisher that replays the event to future subscribers.
func shareReplayOnce(initialValue: Output) -> Publishers.Autoconnect<Publishers.Multicast<Self, CurrentValueSubject<Output, Failure>>> {
multicast { CurrentValueSubject(initialValue) }
.autoconnect()
}
/// A variation on [share()](https://developer.apple.com/documentation/combine/publisher/3204754-share)
/// that allows for buffering and replaying a single event to future subscribers.
///
/// - Returns: A publisher that replays the event to future subscribers.
func shareReplayOnce() -> AnyPublisher<Output, Failure> {
map(Optional.some)
.shareReplay(initialValue: .none)
.compactMap { $0 }
.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment