I create ViewModel with ViewModelProvider.Factory in my fragment. Everthing work fine.
var reportViewModel = ViewModelProviders.of(this,ViewModelProvide(RemoteDataProviderImpl(
WeakReference(context!!))))
.get(ReportViewModel::class.java)
But after i create viewmodel directly with instance and then work everthing fine
var reportViewModel = ReportViewModel(RemoteDataProviderImpl(WeakReference(context!!)))
It is simple ViewModel
class ReportViewModel(private var provider:RemoteDataProvider) : ViewModel(){
var posts = MutableLiveData<List<Report>>()
fun getPost(){
provider.getComments().enqueue(object : Callback<ArrayList<Report>> {
override fun onFailure(call: Call<ArrayList<Report>>, t: Throwable) {
t.message
}
override fun onResponse(
call: Call<ArrayList<Report>>,
response: Response<ArrayList<Report>>
) {
if (response.isSuccessful){
val reports = response.body()
posts.value = reports
}
}
})
}
}
What is difference this two code. If i can create viewModel with directly why i need ViewModelProviders?
ReportViewModel(RemoteDataProviderImpl(WeakReference(context!!)))
will
create a new reference of the viewmodel without any scope of the activity or fragment.
A new reference
of the viewmodel
will be created in onCreate
of the activity. ( even if the activity is rotated or configuration is changed )
It would not observe the scope of the activity ,i.e, it would exist even when the activity is destroyed
!
While
ViewModelProvider.of(this).get(...)
will
Observe
the scope of the activity, i.e, when the activity is finished
, onCleared(..)
of the viewmodel would be called ! ( Viewmodel would be destroyed )
Same instance of the viewmodel
would persist
even during the configuration change
.