Skip to content

Instantly share code, notes, and snippets.

@bitomule
Created July 13, 2019 14:44
Show Gist options
  • Save bitomule/f4312f08866ecefd1262d31703b793a8 to your computer and use it in GitHub Desktop.
Save bitomule/f4312f08866ecefd1262d31703b793a8 to your computer and use it in GitHub Desktop.
final class ReplaySubscriber<Input, Failure: Error>: Subscription {
private var subscriber: AnySubscriber<Input, Failure>?
init(subscriber: AnySubscriber<Input, Failure>) {
self.subscriber = subscriber
}
func request(_ demand: Subscribers.Demand) {
// We do nothing here as we only want to send events when they occur.
// See, for more info: https://developer.apple.com/documentation/combine/subscribers/demand
}
func receive(_ value: Input) {
subscriber?.receive(value)
}
func receive(_ completion: Subscribers.Completion<Failure>) {
subscriber?.receive(completion: completion)
}
func cancel() {
subscriber = nil
}
}
final class ReplaySubject<Output,Failure>: Subject where Failure : Error {
private var subscribers: [ReplaySubscriber<Output, Failure>] = []
private var values: [Output] = []
func receive<S>(subscriber: S) where S : Subscriber, S.Failure == Failure, S.Input == Output {
let subscription = ReplaySubscriber(subscriber: AnySubscriber(subscriber))
subscribers.append(subscription)
subscriber.receive(subscription: subscription)
values.forEach { subscription.receive($0) }
}
public func send(_ value: Output) {
values.append(value)
subscribers.forEach { $0.receive(value) }
}
public func send(completion: Subscribers.Completion<Failure>) {
subscribers.forEach { $0.receive(completion) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment