I'd like to check two APIs consecutively in Reposi...
# coroutines
c
I'd like to check two APIs consecutively in Repository, like this.
Copy code
suspend fun requestChat(hisId: Long): ApiResponse<RequestableResponse>{
        val result = userService.checkRequestableUser(hisId = hisId)
        result.onSuccess {
            if(this.data.message == RequestStatusType.AVAILABLE.name){
                userService.requestChat(RequestChat(respondentId = hisId, chatStarterId = AppConfigure.myId)))
            }
        }
    }
But I get userService.requestChat red line.. because I need to call it in the coroutine. How can I return the value here???
c
I’d update the userservice to provide
checkRequestableUser
without callback.
c
Oh, that's a good idea.
c
You can also have a look at https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/callback-flow.html. But I guess that will not help with our problem here.
c
Oh, Thank you. I tried the first suggestion, but I can't catch the response status.. So, maybe I should find other way. Thank you 🙂
d
For similar scenarios I use
Copy code
Flow
and chain requests together like this:
Copy code
fun fetchedTrackedLaws() {
        val lawCodes = cacheRepository.lawCodes.toTypedArray()
        viewModelScope.launch {
            flowOf(*lawCodes)
                .flatMapMerge { it ->
                    repository.getLawByNumber(it)
                }
                .onStart { state.update { state -> state.copy(isLoading = false) } }
                .collect { result ->
                    when(result) {
                        is Response.Data -> { state.update { state -> state.copy(billsWhichTracked = result.data, isLoading = false) } }
                        is Response.Error -> { state.update { state -> state.copy(errors = state.errors.plus(getErrorMessage(result)), isLoading = false) } }
                    }
                }
        }
    }