Reputation: 4002
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
Reputation: 2515
import kotlin.coroutines.coroutineContext
suspend fun somewhere() {
val scope = CoroutineScope(coroutineContext)
scope.launch { ... }
}
Upvotes: 4
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