'Multiple Requests in Sequential Order - Kotlin Flow - Retrofit
I've two suspend functions:
- login() : BaseResponse
- update() : BaseResponse
I want to use kotlin flow to run both of them with the following scenario:
run login() API and wait till I have the response.
make a check of that response if it's true.
run the second API update().
then collecting the result with the second response.
if an error happened in login() return error and don't run the update() API.
please show a complete simple example of how I do this.
Solution 1:[1]
After searching hours for a solution that suited my case, and I didn't find an answer I'd like to post my answer here after many attempts:
suspend fun login(id: Int): Int {
Timber.e("starting request $id")
delay(2000) // request start
return id // the result shown in collect
}
fun excute() {
GlobalScope.launch {
flow {
val res = login(1) //start request 1
emit(res) // here we emit the res returned from 1 (optional)
if(res == 2){ //make a condition if (success) for request 1
emit(login(2)) // start request 2 when 1 is sucesss
}else{
//return failure
emit(3) // 3 means failure
}
}.collect {
Timber.e("$it")
}
}
}
It seems quite simple and I don't know why I didn't find something similar.
I'd be glad If any has a better approach.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mahmoud Ayman |
