As per As per Android Developer doc
viewModelScope.launch Create a new coroutine on the UI thread and code is as below
class LoginViewModel(
private val loginRepository: LoginRepository
): ViewModel() {
fun login(username: String, token: String) {
// Create a new coroutine on the UI thread
viewModelScope.launch {
val jsonBody = "{ username: \"$username\", token: \"$token\"}"
// Make the network call and suspend execution until it finishes
val result = loginRepository.makeLoginRequest(jsonBody)
// Display result of the network request to the user
when (result) {
is Result.Success<LoginResponse> -> // Happy path
else -> // Show error in UI
}
}
}
}
Does it means if I run a network call inside viewModelScope.launch like a retrofit call will it cause an ANR issue or freeze the UI?
Retrofit ensures that network call from
loginRepository.makeLoginRequest()
is performed via suspending function, which will not block the UI thread while waiting for response from the server. So there will be no ANR.However, a good practice is to dispatch network calls to separate thread/context in place (in your case, in the implementation of
LoginRepository
). This will guarantee that you don't have to worry about network call being executed on a wrong thread. Only data layer will take the responsibility of dispatching the work to the right thread/context.You can switch context or even launch coroutine on a different dispatcher.
[UPD] The example above is actually referred to the official documentation.
And for clearance, it works as follows: