0

I'm having a hard time understand what scopes to use for view models and live data when using fragments. Here is my ViewModel:

class MyViewModel: ViewModel() {

    var myLiveData = MutableLiveData<WrappedResult<DataResponse>>()
    private val repository = MyRespository()
    private var job: Job? = null

    fun getData(symbol: String) {
        job = viewModelScope.launch(Dispatchers.IO) {
            try {
                val response = repository.getData(symbol)
                withContext(Dispatchers.Main) {
                    myLiveData.value = WrappedResult.Success(response)
                }
            } catch(e: Exception) {
                withContext(Dispatchers.Main) {
                    myLiveData.value = WrappedResult.Failure(e)
                }
            }
        }
    }
}

I can create the view model in the fragment using (where "this" is the fragment):

viewModel = new ViewModelProvider(this).get(MyViewModel.class);

However, I can observe the LiveData with two options:

viewModel.getMyLiveData.observe(this...

or

viewModel.getMyLiveData.observe(getViewLifecycleOwner()...

It would appear that the job I create in the view model is going to be scoped to the fragment's lifecycle (through viewModelScope) and not the fragment's view lifecycle, but I have a choice between these two for the live data.

I could use some guidance and what the best practice is here. Also, does any of this matter whether the fragment has retained instance or not? Currently the fragment has setRetainInstance(true). Finally, from everything I've read I shouldn't need to clear the observer in the fragment or override onCleared when things are setup this way. Is that correct?

user982687
  • 325
  • 6
  • 14
  • 1
    You should get your answer here -> https://stackoverflow.com/questions/59521691/use-viewlifecycleowner-as-the-lifecycleowner – Binary Baba Sep 19 '20 at 17:14

1 Answers1

0

refer the doc of view model

https://developer.android.com/topic/libraries/architecture/viewmodel?gclid=Cj0KCQjwtZH7BRDzARIsAGjbK2blIS5rGzBxBdX6HpB5PMKgpUQHvdKXbwrt-ukTnWkpax1otMk4sm4aAuzPEALw_wcB&gclsrc=aw.ds#lifecycle

Viewmodel will only gets destoyed once the activity is finished.As the fragments are on the top of acitivity, the lifecycle of fragment will not affect the Viewmodel.The data will be persisted there on the viewmodel. So you can write a method to reset the data in viewmodel while you are entering in to oncreate of fragment.

In Fragment, OnCreate :

 getViewModel.init()

on ViewModel

fun init() {
// clear all varialbes/datas/ etc here
}
Shiva Snape
  • 544
  • 5
  • 9