Liberty Tom
11/09/2024, 10:35 AMsuspendCancellableCoroutine { continuation ->
val loop = true
val thread = thread {
var result = ""
while(loop) {
// do something
if(...) {
result = "Bala Bala"
break
}
}
continuation.resume(result)
}
continuation.invokeOnCancellation {
try {
loop = false
thread.interrupt()
} catch (e: Exception) {
// do nothing
}
}
}
Alexandru Caraus
11/09/2024, 10:43 AMLiberty Tom
11/09/2024, 10:56 AMCancellationException
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
var result = ""
while(loop) {
// do something
if(...) {
result = "Bala Bala"
break
}
}
result
}
Joffrey
11/09/2024, 11:03 AMloop
here? You should either check isActive
in the condition, or make sure you're using suspend functions in the loop. Cancellation is cooperativeChristian Maier
11/09/2024, 11:47 AMDaniel Pitts
11/09/2024, 3:24 PMyield
within the loopuli
11/11/2024, 12:32 PMwithContext(yourDispatcher) {
while (isActive) {
// do something
if(...) {
result = "Bala Bala"
break
}
}
}
yourDispatcher
can be the best fit of
1. Dispatchers.Default to use the default thread pool
2. Dispatchers.~Default~IO.limitedParallelism(1) to use only on thread from the default pool at a time
3. newSingleThreadContext to create your own thread.
Updated option 2 to use Dispatchers.IO as that will grab a thread from an unlimited pool (not reducing the available IO threads) and probably avoids context switching to Dispatchers.Default and Dispatchers.IO. See Dispatchers.IO, “Elasticity for limited parallelism” and “Implementation note”uli
11/13/2024, 9:28 PMdo something
should be interrupted on cancellation as in your example (thread.interrupt()
), you should wrapp it with runInterruptibleuli
11/13/2024, 9:46 PMwhile (true) {
runInterruptible(yourDispatcher) {
// do something
}
if(...) {
result = "Bala Bala"
break
}
}
And it is good practice to factor the `runInterruptible`out into a single function:
suspend fun doSomething() = runInterruptible(yourDispatcher) {
// do something
}
while (true) {
doSomething()
if(...) {
result = "Bala Bala"
break
}
}