Skip to content

Instantly share code, notes, and snippets.

@zivkesten
Created August 30, 2020 07:24
Show Gist options
  • Save zivkesten/bafc439092c5a79ac7193fe396dd9597 to your computer and use it in GitHub Desktop.
Save zivkesten/bafc439092c5a79ac7193fe396dd9597 to your computer and use it in GitHub Desktop.
Simultanious api call
private fun getUsersFromApi(numOfUsers: Int) {
resultToViewState(Lce.Loading())
try {
viewModelScope.launch(Dispatchers.IO) {
val usersFromApi = mutableListOf<UsersResponse?>()
repeat(numOfUsers) {
//Wait and execute together async
val usersFromApiDeferred = async { repository.getUsers() }
val userFromApi = usersFromApiDeferred.await()
usersFromApi.add(userFromApi)
}
val mutableList = usersFromApi.map {
(it ?: UsersResponse(errorMessage = "Error response"))
.results
.first()
}
val result: Lce<Result> = if (mutableList.isNotEmpty()) {
Lce.Content(Result.UsersResult(mutableList))
} else {
createErrorResponse(java.lang.Exception("Error loading users"))
}
resultToViewState(result)
}
} catch (e: Exception) {
Log.e(MainViewModel::class.java.simpleName, "Error loading users ${e.localizedMessage}")
resultToViewState(createErrorResponse(e))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment