Ilham Bagus Bahrudin
Ilham Bagus Bahrudin

Reputation: 79

why can't i cancel job in kotlin coroutines?

this is when I use the delay function

    @Test
    fun testJob(){
        runBlocking {
            val job = GlobalScope.launch {
                println("Start Coroutine ${Date()}")
                delay(1000)
                println("End Coroutine ${Date()}")
            }
            job.cancel()
            delay(2000)
        }
    }

this is when i use the Thread.sleep function

    @Test
    fun testJob(){
        runBlocking {
            val job = GlobalScope.launch {
                println("Start Coroutine ${Date()}")
                Thread.sleep(1000)
                println("End Coroutine ${Date()}")
            }
            job.cancel()
            delay(2000)
        }
    }

why cancel() can't work when i use Thread.sleep ?

Upvotes: 1

Views: 1101

Answers (2)

Rodrigo Bagni
Rodrigo Bagni

Reputation: 96

delay()'s doc says: "Delays coroutine for a given time without blocking a thread and resumes it after a specified time." But when you call Thread.sleep(), you are delaying the thread itself, which prevents everything else from running on that thread, even other coroutines.

Upvotes: 0

kerelape
kerelape

Reputation: 124

Thread.sleep() is a blocking method, while delay() is a suspend one. Kotlin coroutines may run on a single thread asynchronously, there is a state machine inside, which switches between suspend calls, but when you call Thread.sleep(), it blocks the entire thread.

Upvotes: 2

Related Questions