You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here's an extension function that might be useful to include.
/** * Maps this [Result<V, E>][Result] to [Result<V, E>][Result] by either applying the [transform] * function to the [value][Ok.value] if this [Result] is [Ok<T>][Ok], or returning the result * unchanged.*/publicinlineinfixfun <V, E, reified T:V> Result<V, E>.mapIfInstance(transform: (T) ->V): Result<V, E> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
returnwhen (this) {
isOk-> (value as?T)?.let { Ok(transform(it)) } ?:thisisErr->this
}
}
(that's using the 1.2x library version)
The motivating example is if you have a flow of Result where the OK value is one of a sealed set of subclasses and you typically only want to transform one of them. For example, Data.Loaded in this snippet:
sealedinterfaceData {
data objectLoading : Datadata classLoaded(valdata:String) : Data
}
sealedinterfaceAppError {
data classNetworkError(...)
data classJsonError(...)
// etc
}
Suppose you're processing a flow of Result<Data, AppError>
At the moment, with map, you have to write something like:
theFlow.map {
when (it) {
isData.Loading-> it
isData.Loaded-> { /* some transform here */ }
}
}
[Filtering the flow to just Ok(Data.Loaded) is not necessarily appropriate, as code "downstream" of the flow might still need to distinguish between these cases]
This rapidly gets tedious if you have to do this on every Flow<Result<V, E>>.
With this extension this becomes:
theFlow.mapIfInstance<_, _, Data.Loaded> { /* some transform here */ }
or
theFlow.mapIfInstance { it:Data.Loaded->/* do something */ }
The text was updated successfully, but these errors were encountered:
Here's an extension function that might be useful to include.
(that's using the 1.2x library version)
The motivating example is if you have a flow of
Result
where the OK value is one of a sealed set of subclasses and you typically only want to transform one of them. For example,Data.Loaded
in this snippet:Suppose you're processing a flow of
Result<Data, AppError>
At the moment, with
map
, you have to write something like:[Filtering the flow to just Ok(Data.Loaded) is not necessarily appropriate, as code "downstream" of the flow might still need to distinguish between these cases]
This rapidly gets tedious if you have to do this on every
Flow<Result<V, E>>
.With this extension this becomes:
or
The text was updated successfully, but these errors were encountered: