Last active
October 28, 2019 04:35
-
-
Save rustle/0fdd1a7f90d7d0d4fb7a74bba2c64cf1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension Publisher { | |
/// Assigns each element from a Publisher to a property on an object. | |
/// | |
/// - Parameters: | |
/// - keyPath: The key path of the property to assign. | |
/// - object: The object on which to assign the value. | |
/// - Returns: A cancellable instance; used when you end assignment of the received value. Deallocation of the result will tear down the subscription stream. | |
func assignResult<Root>(to keyPath: ReferenceWritableKeyPath<Root, Result<Self.Output, Self.Failure>>, | |
on object: Root) -> AnyCancellable { | |
sink(receiveCompletion: { completion in | |
switch completion { | |
case .finished: | |
break | |
case .failure(let error): | |
object[keyPath: keyPath] = .failure(error) | |
} | |
}, receiveValue: { value in | |
object[keyPath: keyPath] = .success(value) | |
}) | |
} | |
func unpackResult<ResultSuccess, ResultFailure: Error>() -> AnyPublisher<ResultSuccess, ResultFailure> | |
where Output == Result<ResultSuccess, ResultFailure>, Failure == Never { | |
tryMap { | |
switch $0 { | |
case .success(let value): | |
return value | |
case .failure(let error): | |
throw error | |
} | |
} | |
.mapError { error in | |
return error as! ResultFailure | |
} | |
.eraseToAnyPublisher() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment