https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

myanmarking

02/05/2020, 3:23 PM
basically, it's a timeout for flow, it closes after timedOut
s

streetsofboston

02/05/2020, 3:39 PM
Would something like this work?
Copy code
fun <T> Flow<T>.timeout(millis: Long) = flow {
    this@timeout.collect {
        withTimeout(millis) {
            emit(it)
        }
    }
}
m

myanmarking

02/05/2020, 3:40 PM
hm, the timeout would be to the overall emissions, not on each one. i managed to get this solution. what do you think?
Copy code
fun <T> Flow<T>.timeout(durationInMillis: Long): Flow<T> =
    flow {
        coroutineScope {
            val outerScope = this
            launch {
                try {
                    delay(durationInMillis)
                    outerScope.cancel()
                } catch (e: CancellationException) {
                    outerScope.cancel(e) // cancel outer scope on cancellation exception, too
                }
            }
            collect { emit(it) }
        }
    }
oh wait, cannot be like this
yes, it works. gona write some tests for it
d

Dominaezzz

02/05/2020, 10:04 PM
Copy code
fun <T> Flow<T>.timeout(millis: Long) = flow {
    withTimeout(millis) {
        this@timeout.collect {
            emit(it)
        }
    }
}
m

myanmarking

02/06/2020, 9:53 AM
even better solution. thanks!
9 Views