'Multiple async calls with coroutines when all calls are different
I've got this working but I am not sure if there is a better way to do it. This code is run from an Activity.
enum class HomeApiCalls {
StudyInfo,
Messages,
LessonSummary,
ProgressSummary,
ProgramSummary,
FeedbackSummary
}
fun loadData() {
showLoader()
lifecycleScope.launch {
withContext(Dispatchers.Default) {
val multipleIds = listOf(HomeApiCalls.StudyInfo, HomeApiCalls.Messages, HomeApiCalls.LessonSummary, HomeApiCalls.ProgressSummary, HomeApiCalls.ProgramSummary, HomeApiCalls.FeedbackSummary)
val runningTasks = multipleIds.map { id ->
async {
when(id) {
HomeApiCalls.StudyInfo -> {
val apiResponse = networkMgr.refreshStudyInfo()
id to apiResponse
}
HomeApiCalls.Messages -> {
val apiResponse = networkMgr.refreshMessages()
id to apiResponse
}
HomeApiCalls.LessonSummary -> {
val apiResponse = networkMgr.refreshLessonSummary()
id to apiResponse
}
HomeApiCalls.ProgressSummary -> {
val apiResponse = networkMgr.refreshProgressSummary()
id to apiResponse
}
HomeApiCalls.ProgramSummary -> {
val apiResponse = networkMgr.refreshProgramSummary()
id to apiResponse
}
HomeApiCalls.FeedbackSummary -> {
val apiResponse = networkMgr.refreshFeedbackSummary()
id to apiResponse
}
}
}
}
val responses = runningTasks.awaitAll()
var anyErrors = false
responses.forEach { (id, response) ->
// same failure block for all calls
if (response is Result.Failure) {
anyErrors = true
hideLoader()
showError(response.message ?: "")
return@forEach
}
when(id) {
HomeApiCalls.StudyInfo -> {}
HomeApiCalls.Messages -> {
response.tryCast<Result.Success<MessagesData>> {
messages = this.data!!.getNormalMessages()
lapsedMessages = this.data!!.getLapsedMessages()
}
}
HomeApiCalls.LessonSummary -> {
response.tryCast<Result.Success<LessonSummaryData>> {
lessonSummary = this.data!!
}
}
HomeApiCalls.ProgressSummary -> {
response.tryCast<Result.Success<ProgressSummaryData>> {
progressSummary = this.data!!
}
}
HomeApiCalls.ProgramSummary -> {}
HomeApiCalls.FeedbackSummary -> {
response.tryCast<Result.Success<FeedbackSummaryData>> {
feedbackSummary = this.data!!
}
}
}
}
if(!anyErrors) {
GlobalScope.launch(Dispatchers.Main) {
hideLoader()
refreshHeader()
buildSectionList()
buildListView()
}
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|