Files
GRDB.swift/GRDB/ValueObservation/ValueReducer/CompactMap.swift
T
Gwendal Roué 28c32c6af8 _ValueReducer is the only protocol accepted by ValueObservation
Also, we now use Never as the bottom reducer which helps us define the ValueObservation factory methods.
2020-03-11 21:38:41 +01:00

47 lines
1.7 KiB
Swift

extension ValueObservation {
/// Returns a ValueObservation which notifies the non-nil results of calling
/// the given transformation which each element notified by this
/// value observation.
public func compactMap<T>(_ transform: @escaping (Reducer.Value) -> T?)
-> ValueObservation<ValueReducers.CompactMap<Reducer, T>>
{
return mapReducer { $1.compactMap(transform) }
}
}
extension _ValueReducer {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns a reducer which outputs the non-nil results of calling the given
/// transformation which each element emitted by this reducer.
public func compactMap<T>(_ transform: @escaping (Value) -> T?) -> ValueReducers.CompactMap<Self, T> {
ValueReducers.CompactMap(self, transform)
}
}
extension ValueReducers {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// See ValueObservation.compactMap(_:)
///
/// :nodoc:
public struct CompactMap<Base: _ValueReducer, Value>: _ValueReducer {
private var base: Base
private let transform: (Base.Value) -> Value?
init(_ base: Base, _ transform: @escaping (Base.Value) -> Value?) {
self.base = base
self.transform = transform
}
public func fetch(_ db: Database) throws -> Base.Fetched {
try base.fetch(db)
}
public mutating func value(_ fetched: Base.Fetched) -> Value? {
guard let value = base.value(fetched) else { return nil }
return transform(value)
}
}
}