Search code examples
androidkotlinviewmodel

How to Prevent ViewModel from destroying


I am building an app to save the user details step by step with multiple fragments. I used multiple fragments which shares same view model. But when i am navigating from last fragment to previous fragment ( to edit details that already provided ) the shared ViewModel destroys. Is there any way to prevent it from destroying ?!


Solution

  • If you are using multiple fragments inside a single activity, make use you are providing the ViewModels using the activity context instead of the fragment context.

    In your fragments, it should be like this:

    vm = ViewModelProviders.of(activity!!, vmFactory)[vmclass.java]