ismail M
ismail M

Reputation: 187

How do you make multiple Post Api request and receive multiple responses using retrofit

I want to make multiple Post request sending a list of data and would like to receive each response to check what was submitted successfully or not.

what is the best way to implement this? I tried the following code below

private suspend fun submitConfirmWeights(): Flow<Boolean> = flow {

        syncRepositoryImpl.getOfflineShopCollections().collect {
            it.forEach { weight ->
                val response = confirmWeightsService.confirmWeights(confirmWeightsDtoMapper.mapFromDomainModel(weight))
                if (response.isSuccessful && response.body()?.status == true){
                    emit(true)
                }else{
                    emit(false)
                }
            }
        }

    }

Upvotes: 0

Views: 609

Answers (2)

J.Grbo
J.Grbo

Reputation: 475

Since you're basically converting Flow<Iterable<T>> to Flow<Boolean> your converting function doesn't have to be suspend at all.

private fun getConfirmedWeightsFlow() = syncRepositoryImpl.getOfflineShopCollections().map { collection ->
    coroutineScope {
        collection.map { entry ->
            async {
                val response = confirmWeightsService.confirmWeights(confirmWeightsDtoMapper.mapFromDomainModel(entry))
                response.isSuccessful && response.body()?.status == true
            }
        }
            .awaitAll()
            .all { successful -> successful }
    }
}

And then you can collect from this flow. Everytime a new collection is emitted it would be mapped through newly made requests' statuses to a Boolean value.

Upvotes: 1

Arpit Shukla
Arpit Shukla

Reputation: 10523

You can do it like this:

private suspend fun submitConfirmWeights(): Boolean {
    val collections = syncRepositoryImpl.getOfflineShopCollections().first() // get first emission
    return coroutineScope {
        collections.map { weight ->
            async { // get each response in parallel
                val response = confirmWeightsService.confirmWeights(confirmWeightsDtoMapper.mapFromDomainModel(weight))
                response.isSuccessful && response.body()?.status == true
            }
        }
            .awaitAll()  // wait for all the response
            .all { it }  // check that all are true
    }
}

Upvotes: 1

Related Questions