I just started using MVVM architecture on Android. I have a service which basically fetches some data and updates the UI and this is what I understood from MVVM:
Now as ViewModels should not know anything about the activity and Activities should not do anything other than handling views, Can anyone please tell where should I start a service?
Services provide a specific UI-aware functionality for Views in MVVM applications. Although services are defined within Views, their functionality can still be invoked from View Models that may not even include information about Views.
MVVM was designed to remove virtually all GUI code ("code-behind") from the view layer, by using data binding functions in WPF (Windows Presentation Foundation) to better facilitate the separation of view layer development from the rest of the pattern.
In MVVM, the business logic is built into the Model. The ViewModel is there to bridge between the View and the Model, so it's logic only pertains to driving the display and updating the model from user interactions with the View.
In MVVM, ideally, the methods to start a service should be defined in Repository
since it has the responsibility to interact with Data Source. ViewModel
keeps an instance of Repository
and is responsible for calling the Repository
methods and updating its own LiveData
which could be a member of ViewModel
. View
keeps an instance of ViewModel
and it observes LiveData
of ViewModel
and makes changes to UI accordingly. Here is some pseudo-code to give you a better picture.
class SampleRepository {
fun getInstance(): SampleRepository {
// return instance of SampleRepository
}
fun getDataFromService(): LiveData<Type> {
// start some service and return LiveData
}
}
class SampleViewModel {
private val sampleRepository = SampleRepository.getInstance()
private var sampleLiveData = MutableLiveData<Type>()
// getter for sampleLiveData
fun getSampleLiveData(): LiveData<Type> = sampleLiveData
fun startService() {
sampleLiveData.postValue(sampleRepository.getDataFromService())
}
}
class SampleView {
private var sampleViewModel: SampleViewModel
// for activities, this sampleMethod is often their onCreate() method
fun sampleMethod() {
// instantiate sampleViewModel
sampleViewModel = ViewModelProviders.of(this).get(SampleViewModel::class.java)
// observe LiveData of sampleViewModel
sampleViewModel.getSampleLiveData().observe(viewLifecycleOwner, Observer<Type> { newData ->
// update UI here using newData
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With