Skip to content

Instantly share code, notes, and snippets.

@HarshilShah
Created February 5, 2021 16:00
Show Gist options
  • Select an option

  • Save HarshilShah/c31d414d2b68f939de214201b44402b2 to your computer and use it in GitHub Desktop.

Select an option

Save HarshilShah/c31d414d2b68f939de214201b44402b2 to your computer and use it in GitHub Desktop.
A ReactiveSwift.Property equivalent in Combine
import Combine
import Foundation
final class Property<Value> {
// MARK: Public properties
var value: Value { subject.value }
// MARK: Private properties
private var subject: CurrentValueSubject<Value, Never>
private var cancellable: AnyCancellable?
// MARK: Initializers
init<P: Publisher>(
initialValue: Value, then publisher: P
) where P.Output == Value, P.Failure == Never {
self.subject = CurrentValueSubject(initialValue)
self.cancellable = publisher.subscribe(subject)
}
}
extension Property: Publisher {
typealias Output = Value
typealias Failure = Never
func receive<S>(subscriber: S) where S: Subscriber, S.Input == Output, S.Failure == Failure {
subject.receive(subscriber: subscriber)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment