Hilt: Why is ActivityRetainedScoped vs ViewModelScoped

Viewed 1698

I'm trying to understand why is ActivityRetainedScoped introduced for DI in Hilt. It looks to me that the scope is identical to what ViewModelScoped should do. I was under the impression that scoped worked like this:

AppScope (singleton) > ViewModelScope > ActivityScope > ViewScope > ...

But this graphic kinda hints that ViewModel and Activity scopes are... siblings?

According to the docs:

"ActivityRetainedComponent lives across configuration changes, so it is created at the first Activity#onCreate() and destroyed at the last Activity#onDestroy()."

Well, so does the view model, no? I'm pretty sure view models survive config changes (that's the whole point if having them in the first place)

What is ActivityRetainedScoped? How is it different from VM scope? Why does google likes over complicating things that should be conceptually simple

https://developer.android.com/training/dependency-injection/hilt-android

1 Answers

Well, even tho ActivityRetainedScope and ViewModelScope are Siblings and one could think that makes them the same, there are in fact not.

Well, so does the view model, no? I'm pretty sure view models survive config changes (that's the whole point if having them in the first place)

Well yes, but actually no. A Viewmodel does survive configuration changes, but only of its scoped lifecyleowner. So let's think of the following scenario:

You have two dependencies, one is ActivtyRetainedScoped and the other one is viewmodelscoped.

When you now inject the viewmodeldependency inside the viewmodel and the lifecycleowner of the viewmodel is an activity, then you are right, both the ActivtyRetainedScope and the ViewmodelScope would not make any difference.

But now let's assume the lifecycleowner is a fragment, in this case, the viewmodelscoped dependency would "die" when you navigate out of the fragment and the activtyretainedscope dependency would outlive the viewmodelscoped one.

I hope I could explain the difference between them both. Kinda hard with those "scopes" etc. when English is not your native language. Also, I am not 100% if this is the correct answer

Related