Sam
05/11/2019, 9:11 PM@RunWith(JUnit4::class)
class CoroutineTest {
@Test
fun `test coroutine cancel`() {
var backgroundWorkCanceled = false
runBlocking {
val scope = CoroutineScope( Dispatchers.Default + Job() )
scope.launch {
try {
backgroundWorkCanceled = false
delay(3000)
} catch( e : CancellationException ) {
backgroundWorkCanceled = true
}
}
delay( 2000 )
scope.cancel()
}
assert( backgroundWorkCanceled )
}
}
Sam
05/11/2019, 9:18 PMlouiscad
05/11/2019, 9:25 PMlouiscad
05/11/2019, 9:28 PMrunBlocking
lambda receiver. Consequently, you face a race condition as `runBlocking returns immediately since your prevent the coroutine you launch from being its child that it would wait for.louiscad
05/11/2019, 9:29 PMlaunch(Dispatchers.Default)
instead, if you really need to change the dispatcher.Sam
05/11/2019, 9:31 PMlouiscad
05/11/2019, 10:05 PMSam
05/11/2019, 10:05 PMSam
05/11/2019, 10:05 PM