mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-24 04:07:47 +00:00
We can not tell the compiler that we can safely return `sending` results, because fetched values are in the same region as the `db` argument, according to SE-0414 (https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md#rules-for-merging-isolation-regions). ``` class NotSendable { init() { } } func fetchNotSendable(_ db: Database) -> NotSendable { fatalError() } func notOK<T>(_ make: (Database) -> sending T) { } func ok<T>(_ make: () -> sending T) { } func usage() { ok { NotSendable() } // Returning a task-isolated 'NotSendable' value as a 'sending' result // risks causing data races. notOK { db in fetchNotSendable(db) } } ``` Various attempts at modifying all fetching methods so that they have a `sending` return value have failed.
52 lines
1.8 KiB
Swift
52 lines
1.8 KiB
Swift
extension ValueObservation {
|
|
/// Transforms all values from the upstream observation with a
|
|
/// provided closure.
|
|
///
|
|
/// For example:
|
|
///
|
|
/// ```swift
|
|
/// // Turn an observation of Player? into an observation of UIImage?
|
|
/// let observation = ValueObservation
|
|
/// .tracking { db in try Player.fetchOne(db, id: 42) }
|
|
/// .map { player in player?.image }
|
|
/// ```
|
|
///
|
|
/// The `transform` closure does not run on the main thread, and does not
|
|
/// block any database access This makes the `map` operator a tool that
|
|
/// helps reducing database contention
|
|
/// (see <doc:ValueObservation#ValueObservation-Performance>).
|
|
///
|
|
/// - parameter transform: A closure that takes one value as its parameter
|
|
/// and returns a new value.
|
|
public func map<T>(_ transform: @escaping @Sendable (Reducer.Value) throws -> T)
|
|
-> ValueObservation<ValueReducers.Map<Reducer, T>>
|
|
{
|
|
mapReducer { ValueReducers.Map($0, transform) }
|
|
}
|
|
}
|
|
|
|
extension ValueReducers {
|
|
/// A `ValueReducer` whose values consist of those in a `Base` reducer
|
|
/// passed through a transform function.
|
|
///
|
|
/// See ``ValueObservation/map(_:)``.
|
|
public struct Map<Base: _ValueReducer, Value: Sendable>: ValueReducer {
|
|
private var base: Base
|
|
private let transform: (Base.Value) throws -> Value
|
|
|
|
init(_ base: Base, _ transform: @escaping @Sendable (Base.Value) throws -> Value) {
|
|
self.base = base
|
|
self.transform = transform
|
|
}
|
|
|
|
public func _makeFetcher() -> Base.Fetcher {
|
|
base._makeFetcher()
|
|
}
|
|
|
|
public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Value? {
|
|
guard let value = try base._value(fetched) else { return nil }
|
|
return try transform(value)
|
|
}
|
|
}
|
|
}
|