MiddleCodeCommonNot answered yet
Wrap a one-shot callback API in a Future, and a delegate callback stream in a subject-backed publisher
Bridge two non-Combine APIs into publishers:
loadUser(completion: @escaping (Result<User, Error>) -> Void)fires exactly once.- A
LocationDelegatecallsdidUpdate(_ location: Location)many times.
Requirements:
and expose it as a read-only publisher.
- Wrap
loadUserin aFuture<User, Error>. - Back the delegate stream with a
PassthroughSubjectthe delegate sends into,
func userPublisher() -> AnyPublisher<User, Error> {
// your code here — wrap loadUser in a Future
}
final class LocationStream {
// your code here — PassthroughSubject + exposed publisher + delegate hook
}
Write the implementation.
Use a Future for one-shot: run loadUser and pass its Result to promise; it fires once and caches it. For the delegate, hold a private PassthroughSubject, send(_:) per callback, and expose eraseToAnyPublisher() — read-only for callers.
- ✗Reaching for a
Futurefor a multi-value delegate stream - ✗Exposing the
PassthroughSubjectinstead of an erased read-only publisher - ✗Expecting a
Futureto re-run its closure on each subscription
- →Why does a
Futurecache and replay its single result? - →How would you back the delegate stream with
CurrentValueSubjectinstead?
func userPublisher() -> AnyPublisher<User, Error> {
Future { promise in
loadUser { result in promise(result) }
}
.eraseToAnyPublisher()
}
final class LocationStream {
private let subject = PassthroughSubject<Location, Never>()
var locations: AnyPublisher<Location, Never> { subject.eraseToAnyPublisher() }
func didUpdate(_ location: Location) {
subject.send(location)
}
}
A Future calls its promise once and caches that single result, replaying it to any subscriber. A PassthroughSubject turns an open-ended delegate callback into a stream: each didUpdate becomes subject.send, and callers subscribe to the erased publisher without being able to send into it.