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

wakingrufus

07/27/2018, 8:10 PM
if i have an
Copy code
async {
     while(isActive){
         ....
     }
    return "something"
}
how can I cancel it so that I can call
await
without getting a cancellation exception?
Well that's not really the behavior I want. Maybe I am using the wrong approach, but what I want is something that runs forever until I tell it to stop, and then when I do, it returns successfully with information on what it did
d

dave08

07/30/2018, 11:22 AM
So you could just catch the exception and return the value there... CancellationException is not an error, but rather a way to exit a running Coroutine. Btw,
async
is not like
launch
in that if there's an exception, it bubbles it out to the caller, whereas
launch
"swallows" it.
Copy code
async {
    return try {
     while(isActive){
         ....
     }

        throw IllegalStateException("Not supposed to reach here")
    } catch(e: CancellationException) {
          "something"
   }
}
w

wakingrufus

07/30/2018, 4:04 PM
ok I'll try this thanks!
5 Views