Skip to content

Instantly share code, notes, and snippets.

@daltonclaybrook
Last active July 19, 2019 03:16
Show Gist options
  • Save daltonclaybrook/d42dffe77122364802720cc4155567a2 to your computer and use it in GitHub Desktop.
Save daltonclaybrook/d42dffe77122364802720cc4155567a2 to your computer and use it in GitHub Desktop.
A Swift property wrapper which conforms to Publisher and emits before the wrappedValue has been set
import Combine
@propertyWrapper
struct NextValue<Output> {
typealias Failure = Never
typealias Publisher = AnyPublisher<Output, Never>
var wrappedValue: Output {
willSet {
subject.send(newValue)
}
}
var projectedValue: Publisher {
subject.eraseToAnyPublisher()
}
private let subject = PassthroughSubject<Output, Never>()
init(initialValue: Output) {
self.wrappedValue = initialValue
}
}
@daltonclaybrook
Copy link
Author

daltonclaybrook commented Jul 19, 2019

Usage:

import Combine
import SwiftUI

final class ContentViewModel: BindableObject {
	@NextValue var model = "Foo Bar"
	var willChange: NextValue<String>.Publisher { $model }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment