Sobes.tech
Junior — Middle

How do you implement network requests using ViewModel in an application?

sobes.tech AI

Answer from AI

To perform network requests in an Android application using ViewModel, the MVVM architecture and libraries such as Retrofit and Coroutines are typically used.

Main idea:

  • ViewModel contains the logic for data loading and manages UI state.
  • Network requests are performed asynchronously to avoid blocking the main thread.
  • Request results are passed to the View via LiveData or StateFlow.

Example using Kotlin Coroutines and Retrofit:

class MyViewModel(private val repository: MyRepository) : ViewModel() {
    private val _data = MutableLiveData<ResultType>()
    val data: LiveData<ResultType> = _data

    fun fetchData() {
        viewModelScope.launch {
            try {
                val response = repository.getDataFromNetwork()
                _data.value = response
            } catch (e: Exception) {
                // Error handling
            }
        }
    }
}

class MyRepository(private val apiService: ApiService) {
    suspend fun getDataFromNetwork(): ResultType {
        return apiService.fetchData()
    }
}

Here, viewModelScope automatically cancels the coroutine when the ViewModel is destroyed, preventing memory leaks. This approach ensures a clean separation of concerns and ease of testing.