@@ -146,6 +146,35 @@ extension LoadableState {
146146 case . loaded( let data) : try . loaded( transform ( data) )
147147 }
148148 }
149+
150+ // MARK: - compactMap
151+
152+ /// Transforms the current `LoadableState` with a specified value type to a new `LoadableState`
153+ /// with a different value type.
154+ ///
155+ /// This method applies a transformation function to the loaded value of the current state,
156+ /// if available, and returns a new `LoadableState` instance with that transformed value.
157+ /// If the current state is `absent`, `loading`, or `error`, it returns the same state
158+ /// without applying the transformation.
159+ ///
160+ /// - Parameter transform: A closure that takes the current value of type `Value` and returns a
161+ /// new value of type `T?`. If the result of the transform is nil `absent` will be returned as resulting state.
162+ /// The closure can throw an error, in which case the method will rethrow it.
163+ /// - Returns: A new `LoadableState` instance with the transformed value of type `T`,
164+ /// or the same state if the current state is `absent`, `loading`, or `error`.
165+ /// - Throws: Rethrows any error that the `transform` closure might throw.
166+ public func compactMap< T> ( _ transform: ( Value ) throws -> T ? ) rethrows -> LoadableState < T > {
167+ switch self {
168+ case . absent: return . absent
169+ case . loading: return . loading
170+ case . error( let error) : return . error( error)
171+ case . loaded( let value) :
172+ if let transformed = try transform ( value) {
173+ return . loaded( transformed)
174+ }
175+ return . absent
176+ }
177+ }
149178}
150179
151180extension LoadableState : Sendable where Value: Sendable { }
0 commit comments