I am trying to create a Flow that emits a value after a timeout, without cancelling the underlying coroutine. The idea is that the network call has X time to complete and emit a value and after that timeout has been reached, emit some initial value without cancelling the underlying work (eventually emitting the value from the network call, assuming it succeeds).
Something like this seems like it might work, but it would cancel the underlying coroutine when the timeout is reached. It also doesn't handle emitting some default value on timeout.
val someFlow = MutableStateFlow("someInitialValue")
val deferred = async {
val networkCallValue = someNetworkCall()
someFlow.emit(networkCallValue)
}
withTimeout(SOME_NUMBER_MILLIS) {
deferred.await()
}
I'd like to be able to emit the value returned by the network call at any point, and if the timeout is reached just emit some default value. How would I accomplish this with Flow/Coroutines?