Hey I am trying to create a flow operator to catch...
# coroutines
u
Hey I am trying to create a flow operator to catch with a reference to the previous value. Basically a extended version of existing
catch
operator. But the lambda should get error as well the previous item This is what i have at the moment 👇. I need help to make it functional.
Copy code
public fun <T> Flow<T>.catchWithReferenceToLastValue(
    action: suspend FlowCollector<T>.(item: T?, cause: Throwable) -> Unit
): Flow<T> = flow {
    var previousValue: T? = null
    collect { value ->
        previousValue = value
        emit(value)
        catch { cause -> action(previousValue, cause) }
    }
}
Ok i got it to work i think
Copy code
public fun <T> Flow<T>.catchWithReferenceToLastValue(
    action: suspend FlowCollector<T>.(item: T?, cause: Throwable) -> Unit
): Flow<T> {
    var previousValue: T? = null
    return flow {
        collect { value ->
            previousValue = value
            emit(value)
        }
    }.catch { cause -> action(previousValue, cause) }
}