Junior — Middle
How do you implement data transfer from repository to ViewModel?
sobes.tech AI
Answer from AI
To transfer data from a repository to a ViewModel in Android, the architectural pattern MVVM and components like Jetpack's LiveData or Flow are typically used.
Main idea:
- The repository provides data, for example from a database or network, in the form of LiveData or Flow.
- The ViewModel subscribes to this data and stores it in its fields.
- The UI (Activity or Fragment) observes the LiveData from the ViewModel and updates the interface when data changes.
Example using LiveData:
class UserRepository {
fun getUserData(): LiveData<User> {
// Returns LiveData from database or network
}
}
class UserViewModel(private val repository: UserRepository) : ViewModel() {
val userData: LiveData<User> = repository.getUserData()
}
// In Activity or Fragment
viewModel.userData.observe(viewLifecycleOwner) { user ->
// Update UI with new user data
}
This approach ensures reactive UI updates when data changes and a clear separation of responsibilities between application layers.