Sudar Nimalan
Sudar Nimalan

Reputation: 4002

Kotlin Coroutines How to get CoroutineScope for the current Thread?

In Kotlin Coroutines, want to create a reference for the current thread and use it later.

fun myFuncion(){
    //save current Thread CoroutineScope
    var currentCoroutineScope : CoroutineScope // <How to create?>
    GlobalScope.launch { 
        //Do something 001
        currentCoroutineScope .launch {
            //Do something 002

        }
    }
}

Could anyone help with this?

Upvotes: 11

Views: 13182

Answers (2)

milan
milan

Reputation: 2515

import kotlin.coroutines.coroutineContext

suspend fun somewhere() {
  val scope = CoroutineScope(coroutineContext)
  scope.launch { ... }
}

Upvotes: 4

Atiq
Atiq

Reputation: 14835

You can save a reference to a Coroutines scope using

val scope = CoroutineScope(Dispatchers.Default)

and then you can use it like

fun myFuncion() {
    scope.launch {
        // do something
    }
}

Update from comments:

if you are calling your myFunction() from main thread then you can do something like this

fun myFuncion() {
        scope.launch {
            // do something
            withContext(Dispatchers.Main) { 
                //Do something 002
            }

        }
    }

Upvotes: 2

Related Questions