Zouyiu Ng
Zouyiu Ng

Reputation: 193

GlobalScope.launch(coroutineContext) vs launch() in a class extends CoroutineScope

As codes shown below,

  1. Will two launchWithXXX functions run in MainScope? Are they creating the same coroutine environment for running both jobs?
  2. Will both functions be canceled when dispose() is called?
class A : CoroutineScope by MainScope() {

    fun launchWithGlobalScope() {
        GlobalScope.launch(coroutineContext) {
            // Run jobs
        }
    }

    fun launchWithClassScope() {
        launch {
            // Run jobs too
        }
    }

    fun dispose() {
        cancel()
    }
}

Upvotes: 0

Views: 1391

Answers (1)

Rene
Rene

Reputation: 6258

Answer for 1: No. MainScope defines a scope for doing something with UI components. So it runs in the UI thread of your platform. GlobalScope is a scope with an own thread pool and runs the coroutine with one of those threads.

Answer for 2: cancel does only stop the MainScope in your example and all coroutines created with this scope.

Upvotes: 4

Related Questions