JakeWharton/retrofit2-kotlin-coroutines-adapter

Thread is different first and next

tonyjs opened this issue ยท 1 comments

here is my code

class HelloRepository(api: HelloApi) {
    suspend fun getHello() {
        Log.e("start", "thread id = ${Thread.currentThread().id}")
        val hello = api.getHello().await()
        Log.e("end", "thread id = ${Thread.currentThread().id}")
    }
}

class HelloUseCase(repository: HelloRepository) {
    fun execute(onComplete:(Hello) -> Unit) : Job {
        job = Job()
        CoroutineScope(Dispatchers.Main + job).launch {
            onComplete(repository.getHello())
        }
        return job
    }
}

class ViewModel {
    // execute on activity create
    fun getHello() {
        jobs += helloUseCase.execute(...)
    }
}

// And then cancel the job on actvitiy destroy
class Activity {
    onDestoy() {
        jobs.forEach {
            it.cancelChildren()
            it.cancel()
        }
    }
}

the log App on launch
start thread id = 123
end thread id = 123

the log app on re-launch(press back key and click app shortcut)
start thread id = 123
end thread id = 126

Why the Thread is different first launch and then next launch?

Because coroutine is run within a job. When you call await(), this job release a current thread and return back to a job queue. After response is received, an arbitrary free thread from pool is used to continue this job.