0

I would like to modify the default Flow.catch function and always call a specific suspend function logOutIfUserHasNoAccount(). My current implementation is:

private suspend fun <T> Flow<T>.catchLoginError(action: suspend FlowCollector<T>.(Throwable) -> Unit): Flow<T> {
    logOutIfUserHasNoAccount()
    return catch(action)
}

My questions is: Is there any disadvantage that my Flow.catchLoginError function is also a suspend function? The default implementation of catch is:

// Not suspending
public fun <T> Flow<T>.catch(action: suspend FlowCollector<T>.(Throwable) -> Unit): Flow<T> { /* compiled code */ }

Using

suspend fun login() = flow {

}.catchLoginError( e -> 
 // here it should call "logOufIfUserHasNoAccount" first
 doStuff(e) 

}

Andrew
  • 4,264
  • 1
  • 21
  • 65
  • Do you only want to log out if there's an error? As is, your function will always log out before Flow collection even begins. – Tenfour04 Jul 02 '21 at 14:46
  • In that case, my function is wrong. I only want to logout if there is an error! – Andrew Jul 02 '21 at 14:56

1 Answers1

2

Your function when called immediately calls the logout function, and then returns a wrapped version of the original Flow that will catch errors when it is collected.

To logout only when errors occur, you should move the call inside the catch call's block. It doesn't need to be a suspend function either.

fun <T> Flow<T>.catchLoginError(action: suspend FlowCollector<T>.(Throwable) -> Unit): Flow<T> = catch { error ->
    logOutIfUserHasNoAccount()
    action(error)
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154