Home > OS >  How to start a coroutine on main thread without using GlobalScope?
How to start a coroutine on main thread without using GlobalScope?

Time:02-26

Whenever I want to start a coroutine on a main thread,

fun main(args: Array<String>) {
    GlobalScope.launch {
        suspededFunction()
    }
}

suspend fun suspededFunction() {
    delay(5000L) //heavy operation
}

GlobalScope is highlighted, and always taunt that its usage is delicate and require care.

What delicacies are involved with GlobalScope, and importantly how can I start a coroutine without using GlobalScope?

CodePudding user response:

To start coroutine without using a GlobalScope, one can do as:

val job = Job()
val scope = CoroutineScope(job)

scope.launch {
        suspededFunction()
    }

As mentioned in comments, some classes already have scopes available, like ViewModel class as viewModelScope.

in Activity or Fragment you can as follows:

//not recommended to use co-routines inside fragment or activity class
// this is just for example sack shown here.
// otherwise you have to do all your processing inside viewmodel
    class Fragment : CoroutineScope by MainScope() {
             
            
        ... 
             override fun onDestroy() {
                super.onDestroy()
                cancel()
             }
        
        }

CodePudding user response:

Kotlin already created some scope. you can use it according to your situation. and you also create your own scope. but I suggest in the beginning it is better to use that already created check official documentation https://developer.android.com/topic/libraries/architecture/coroutines in Activity you can use lifecycleScope or inside viewmodel you can use viewModelScope

  • Related