I am using MVVM architecture in my application and i want to make API requests from the activity's viewmodel class. The problem here is I am not getting the best way to do so. As viewmodel is already lifecycle aware for that activity so there is no need to make a separate viewmodel class for the API's? If this is so then should i fire the normal retrofit requests from the viewmodel class or what would be the best approach in this scenario?
What i was doing earlier without MVVM is this:
class UserViewModel : ViewModel() {
private val cd = CompositeDisposable()
val status: MutableLiveData<Boolean>? = MutableLiveData<Boolean>()
val responseImages = MutableLiveData<ResponseImages>()
fun getImages(text: String) {
cd.add(
RetrofitHelper.apiInstance.getImages(Site.METHOD, Site.KEY, text)
.myApiSubscriber(status)
.subscribe({
responseImages.postValue(it)
}, {
it.printStackTrace()
})
)
}
private fun <T> Single<T>.myApiSubscriber(status: MutableLiveData<Boolean>?): Single<T> {
return this.doOnSubscribe {
status?.postValue(true)
// Utils.debugger("PROGRESS ", " doOnSubscribe")
}.doFinally {
status?.postValue(false)
// Utils.debugger("PROGRESS ", " doFinally")
}.subscribeOn(Schedulers.io())
}
override fun onCleared() {
cd.dispose()
super.onCleared()
}
fun callCleared() {
onCleared()
}
}
so is the above way is still useful in case of MVVM or not and what's the best approach to follow with MVVM? Please suggest.