https://kotlinlang.org logo
#dagger
Title
# dagger
a

Archie

09/14/2020, 10:11 AM
In Hilt is there a way to have a dependency scoped to
@ActivityRetainedScoped
but have a value injected to it from the
Activity
. I need the depedency to survive device rotation but the problem is it also needs a value taken from the `Activity`'s bundle. Any advise on how to work around this?
a

allan.conda

09/14/2020, 10:25 AM
How about injection via setter?
a

Archie

09/14/2020, 10:26 AM
Do you mean,
Copy code
@Inject
lateinit var myObject: MyObject

...

myObject.setValue(someValueFromBundle)
??
a

allan.conda

09/14/2020, 10:27 AM
yep
Or use a ViewModel and savedStateHandle
Copy code
class MyViewModel @ViewModelInject constructor(
  @Assisted savedStateHandle: SavedStateHandle // your bundle args is here
): {
  private val myArg = savedStateHandle.get("arg_key")
}
a

Archie

09/14/2020, 10:36 AM
the problem is that the inject value from the activity bundle should only work as the initial value... overtime that value would change.. now if the activity gets recreated because of device rotation... it value would be reset to the initial value from the bundle
a

allan.conda

09/14/2020, 10:38 AM
for viewmodel inject, it works as you want it. For setter injection, it’s just a matter of checking for
savedInstanceState == null
a

Archie

09/14/2020, 10:40 AM
I guess I will need to restructure the project to make this work. use
ViewModel
to hold the states instead of just a scoped object. making
ViewModel
hold states is probably the correct way anyway.
a

allan.conda

09/14/2020, 10:43 AM
ActivityRetainedComponent is meant specifically for ViewModel
a

Archie

09/14/2020, 10:43 AM
Anyway thanks for the inputs i really appreacite it
a

allan.conda

09/14/2020, 10:43 AM
no problem
2 Views