https://kotlinlang.org logo
Title
a

Allan Wang

09/27/2020, 10:16 AM
For flows, we can collect for x seconds by doing
withTimeoutOrNull(time) {
  flow.collect { ... }
}
Is there a way to do this in the middle of the flow, such that the function still returns
Flow<T>
?
c

coroutinedispatcher

09/27/2020, 10:36 AM
It seems like the documentation says as you have written: https://kotlinlang.org/docs/reference/coroutines/flow.html#flow-cancellation-basics
a

Allan Wang

09/27/2020, 1:53 PM
I understand that part. I was wondering for cases where I want to return
Flow<T>
for other calls, as I won’t be collecting values yet
b

bezrukov

09/27/2020, 2:20 PM
you can write simple extension:
fun <T> Flow<T>.withTimeout(timeMillis: Long): Flow<T> = flow {
    withTimeoutOrNull(timeMillis) {
        collect { 
            emit(it)
        }
    }
}
in this case you literally do this in the middle of the flow
👍 4
a

Allan Wang

09/27/2020, 2:45 PM
cool! totally forgot that you can emit while collecting