Hi, can anyone show me how to wait for a deferred ...
# coroutines
j
Hi, can anyone show me how to wait for a deferred with a timeout but allow the deferred to continue without a cancellation or timeout exception from the surrounding context?
What I thought would work
j
Copy code
val deferred = TODO("whatever gives you the deferred, maybe an async{} call")
val value = withTimeoutOrNull(1000) { deferred.await() }
if (value == null) {
    // handle the timeout
} else {
    // use the deferred value
}
j
Copy code
try {
  withTimeout(5000) {
    deferred.await()
  }
catch(t: TimeoutException) {
  emit(TimedOut) // let people know to use cache
  val finishedResult = deferred.await()
  emit(finishedResult)
}
will
withTimeoutOrNull
cancel the deferred though? Thats what i am getting as an exception, that I am trying to do something in a cancelled context violating exception transparency
j
No it doesn't cancel the deferred, it only cancels the suspending functions inside its own block
{ ... }
(so the
await
call in this case), but the deferred itself is controlled by whatever scope you ran it with: https://pl.kotl.in/AW8gJcbu_
j
okay thanks, i'll mess around with my solution then
j
Note that your solution also should work. Maybe something else is wrong for you: https://pl.kotl.in/C6c8KzzZL
j
ya thats what i am thinking