Android ActivityViewModels - what happens when activity is destroyed

365 Views Asked by At

I am trying to understand a bit of a scenario where we have a viewmodel created using ktx-library extension activityViewModels.

I understood that it can be used by fragments that wants to share viewmodel with other fragments within the same activity. This is how I am creating my viewmodel:

    @Inject
    lateinit var viewModelFactory: SortToContainerViewModelFactory
 

    private val viewModel: SortToContainerViewModel by activityViewModels {
        viewModelFactory
    }

How I am accessing in second fragment:

private val sharedViewModel: SortToContainerViewModel by activityViewModels()

Everything works fine when I am running the app and using it. But if for some reason activity gets destroyed when app has been put to background, and I try to access the app and be on second fragment screen , I see this crash:

FATAL EXCEPTION: main                                                                

                                                                                                   

java.lang.RuntimeException: Unable to resume activity {com.doddle.receivesort.us.inmar.stage/com.a..activity.xxActivity}: 

java.lang.RuntimeException: Cannot create an instance of class com.a.concession.workflow.sorting.features.SortParcelToContainerViewModel


Any idea as to what can we do to prevent this crash?

1

There are 1 best solutions below

0
On BEST ANSWER

Generally whenever you're "getting" the viewmodel you have to ensure you're providing the same factory in all places in case it does need to be (re)created. You're not doing that so you only happen to get exising instance of viewmodel from viewModelStore when navigating but when activity is restarted it crashes because viewmodel cannot be recreated (using default factory).

That's why raw dagger is bad for android and I highly recommend you use it with Hilt instead - that way all by viewModels and by activityViewModels calls will be automatically injected with factory appropriate for each viewmodel.