Home > front end >  Unable to observe Viewmodel from one fragment but works from different fragment in Android [Kotlin]
Unable to observe Viewmodel from one fragment but works from different fragment in Android [Kotlin]

Time:09-18

In a weird scenario, I am able to fetch the response from an API and see it in one of the fragments by observing the livedata from viewmodel but it doesn't show any response in a different fragment.

I have a fragment where I put some values and these values are further pass through viewmodel -> repository to fetch the data from an api and then I am observing this data using a variable in different fragments.

I am only able to fetch the data in the fragment from where I am sending values but unable to observe from other fragments.

Any possible reason for this?

P.S - If there is any requirement of code let me know I'll add.

Edit 1 : Figured out that there is something called as Shared ViewModel that should be used. So I tried implementing that. Only thing I had to change was changing my viewModel implementations to activityViewModels. But things doesn't seems to be working still.

Not sure but maybe there can be an issue with my implementation of ViewModel across the app.

Currently I follow this pattern. Data from api -> Repository (I pass the api in its constructor) -> ViewModel (I pass the repository in its constructor).

As I am passing repository instance in my constructor of the ViewModel I have created a ViewModelFactory which passes the repository when ViewModel is created.

Keeping all this in mind, I have created a global initialization of repository inside the MainApplication class like this :

val myRepoInstance by lazy { myReposiotry(myApiClient) }

and I am implementing it inside the fragment like this :

    private val myViewModelInstance: MyViewModel by activityViewModels {
        ViewModelFactory((context?.applicationContext as MainApplication).myRepoInstance)
    }
//Rest of the code...

CodePudding user response:

You need Factory in you first Fragment only not in your second fragment

For First Fragment do this

private val viewModel: SharedViewModel by activityViewModels { SharedViewModel.Factory(...) }

For second fragment do this(don't create factory)

private val viewModel: SharedViewModel by activityViewModels()

For this link for details FragmentAenter image description here

enter image description here [ShareViewModel][2] [FragmentBFragmentA

  • Related