https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

bobby

11/11/2020, 10:17 AM
Hi All, I had a code looks like below
Copy code
fun main() {
    viewModelScope.launch {
        doA()
        //call api with Flow as the return type
    }
}

suspend fun doA() {
    viewModelScope.async { doB() }.await()
}

suspend fun doB() {
    //Do logic here, eventually will call line below
    viewModelScope.launch { doC() }
}

suspend fun doC() {
    //call api with Flow as the return type
}
What I want to achieve from the code above is to wait for the
doA()
function to finished and then continue to call the API, but when I tried to run the code, the
doA()
is executed first but it continue to call the API rather than waiting for the
doA()
to finish. Is there's something wrong with the code? Yes, the code is quite bad, I still kind a new with the Coroutine, thanks for helping, really appreciate it
n

Naoki Hidaka

11/11/2020, 10:57 AM
Do you want to wait to finish the doA()?
b

bobby

11/11/2020, 10:58 AM
yap, that's what I want to achieve here
n

Naoki Hidaka

11/11/2020, 11:00 AM
How about this?
Copy code
fun main() {
    viewModelScope.launch {
        async { doA() }.await
    }
}
b

bobby

11/11/2020, 11:02 AM
what's the difference between your suggestion with code below?
Copy code
fun main() {
    viewModelScope.launch {
        async { doB() }.await()
    }
}
n

Naoki Hidaka

11/11/2020, 11:02 AM
No differene
b

bobby

11/11/2020, 11:03 AM
ok than, I'll try
I had tried your solution but it didn't working like what I want to achieve, the code below
doA()
which is the call API still run without waiting the
doA()
finish. I think because at the
doB()
I created new scope that I think works separate with the scope in
main()
4 Views