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?
First, make sure that the function
makeLoginRequestis a suspend function.Second, make sure that the code you are calling inside of it is actually suspendable.
If you are using Retrofit, the request interface is already implemented as a suspend function by default, so it is safe to use it.
Let's say that you were using OkHttp or any different library that still does some heavy task and does not implement a suspend function.
[UPDATE] The reference documentation is actually the link you posted in the question, but just down below "Use Coroutines for Main Safety" and the example below is based on it. Find it here
In this case, the safest way to do it would be something like this:
In this case,
withContextguarantees that the code inside of this block is executed in an IO thread, which is appropriate for this kind of operations and the execution becomes suspended (not blocking) until the operation terminates. Only after is the function returning and the execution continues on the viewModelScope.This is a simple way to convert non-suspending code to suspending.