SMGhost
SMGhost

Reputation: 4037

Kotlin coroutines not running launch on main

I have following code:

 Timber.d("Calling coroutine from thread: ${Thread.currentThread().name}")
    scope.launch {
        Timber.d("Current thread: ${Thread.currentThread().name}")
        runTest()
    }

 suspend fun runTest() {
    coroutineScope {
        launch(Dispatchers.Main) {
            Timber.d("Running from thread: ${Thread.currentThread().name}")
        }
    }
}

If I run it. App crashes with no error in log. In my log I see:

Calling coroutine from thread: main

Current thread: DefaultDispatcher-worker-2

But I don't see entry with Running from thread:

This is done in viewmodel My scope looks like this:

val scope: ViewModelCoroutineScope = ViewModelCoroutineScope(Dispatchers.Default)

class ViewModelCoroutineScope(
    context: CoroutineContext
) : CoroutineScope {

    private var onViewDetachJob = Job()
    override val coroutineContext: CoroutineContext = context + onViewDetachJob

    fun onCleared() {
        onViewDetachJob.cancel()
    }
}

What am I doing wrong?

Upvotes: 1

Views: 3084

Answers (1)

SMGhost
SMGhost

Reputation: 4037

Moving to a different machine I finally got some errors about Dispatchers.MAIN not working.

In the end all I had to do was replace all raw coroutine dependencies with:

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1")

Upvotes: 1

Related Questions