Requiring a Publisher with a current value

Viewed 362

Both CurrentValueSubject and @Published.Publisher (retrieved via $ from an ObservableObject property) immediately send a notification with the current value when a new subscriber is added (verified with this example).

Is there a way to require this behaviour with a protocol?

For example, if you offer an initializer that requires to pass a publisher, one would use AnyPublisher here:

init(settings: AnyPublisher<Settings, Never>) {
    // ...
}

This would allow to be sneaky and pass in a PassthroughSubject erased to AnyPublisher. Is there a way to prevent this that would allow to pass in both a CurrentValueSubject or an @Published property? (something like a AnyValuePublisher?)

1 Answers

There is no way to know up-ahead which Publisher will replay its latest value vs. which will not (since a custom publisher could do the same, too).

The only thing I can think of in this specific use case is a ghost protocol to only mark these two types for this use case:

protocol ReplayingPublisher: Publisher {}

extension CurrentValueSubject: ReplayingPublisher {}
extension Published.Publisher: ReplayingPublisher {}

struct MyObject {
    init<P: ReplayingPublisher>(publisher: P) {
        // P is only one of these two possible options
    }
}
Related