// Copyright © 2020 Metabolist. All rights reserved. import Foundation import Combine extension Publisher { func assignErrorsToAlertItem( to keyPath: ReferenceWritableKeyPath, on object: Root) -> AnyPublisher { self.catch { [weak object] error -> Empty in DispatchQueue.main.async { object?[keyPath: keyPath] = AlertItem(error: error) } return Empty() } .eraseToAnyPublisher() } func continuingIfWeakReferenceIsStillAlive(to object: T) -> AnyPublisher<(Output, T), Error> { tryMap { [weak object] in guard let object = object else { throw WeakReferenceError.deallocated } return ($0, object) } .tryCatch { error -> Empty<(Output, T), Never> in if case WeakReferenceError.deallocated = error { return Empty() } throw error } .eraseToAnyPublisher() } } private enum WeakReferenceError: Error { case deallocated }