Created
August 30, 2020 07:24
-
-
Save zivkesten/bafc439092c5a79ac7193fe396dd9597 to your computer and use it in GitHub Desktop.
Simultanious api call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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