I'm trying to figure out how to launch a coroutine. I want it to call two suspend functions in sequence.
The first docs I read said to do this:
class Something {
fun initialize() {
launch {
suspendFun1()
suspendFun2()
}
}
But the launch
method was not found by Android Studio. Then I learned that the official coroutine docs suggest using GlobalScope.launch
:
class Something {
fun initialize() {
GlobalScope.launch {
suspendFun1()
suspendFun2()
}
}
But then I read in this post that you should not use GlobalScope.launch
.
So I found another blog post explaining that I need a CoroutineScope to call launch
. But it doesn't explain how to build one.
Then I found this blog post explaining how to build one for Activities and ViewModels, by implementing CoroutineScope on the class:
class Something : CoroutineScope {
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
fun initialize() {
job = Job()
launch {
suspendFun1()
suspendFun2()
}
}
Then I read this blog post saying I should not implement CoroutineScope
class Something {
protected val scope = CoroutineScope(
Job() + Dispatchers.Main
)
fun initialize() {
scope.launch {
suspendFun1()
suspendFun2()
}
}
But I'm not sure I understand the meaning of Job() + Dispatchers.Main
, as this seems to work as well:
class Something {
protected val scope = CoroutineScope(Dispatchers.Main)
fun initialize() {
scope.launch {
suspendFun1()
suspendFun2()
}
}
Can someone explain to me simply the best way to do this? Is it as above? I'm sure this has been asked already, so I apologize if this is a duplicate question. But as you can see, there are not clear answers on this. I would like to hear your input.