'Get directly an instance from Hilt
I inject MyObject in FirstFragment by Hilt, This fragment replaces with another fragment, and as well as you know, when one fragment is replaced with another, onDestroyView() called and when you press back, the view will be created again.
I need to create a new instance of MyObject whenever the fragment's view is created. in Koin I could get directly an instance inside of my code with get<MyObject>() but in Hilt, I couldn't find anything and I have to inject it as a constructor or property.
I also tried to use ViewWithFragmentComponent to change my scope, but I get an error when I use this instead of ApplicationComponent
How can I have a new instance of MyObject whenever my view created in my fragment?
@AndroidEntryPoint
class FirstFragment : BaseFragment(){
@Inject lateinit var myObject: MyObject
}
@InstallIn(ViewWithFragmentComponent::class)
@Module
object MyModule{
@Provides
internal fun provideMyObject(): MyObject {
...
}
}
Solution 1:[1]
As far as I know, whenever you inject something into a fragment and this fragment gets destroyed, the injected object gets destroyed as well. So in your example, when onDestroyView() is called myObject will be garbage collected. Clicking the back button then will trigger onCreateView() and dagger-hilt will automatically provide a new instance of myObject.
If you always want the same object, you have to annotate it with @Singleton. Optional, you can also use @FragmentScoped, where the documentation says:
Scope annotation for bindings that should exist for the life of a fragment.
But to my mind, this is not needed as I personally found at that an object provided by dagger-hilt gets recreated when the fragments gets recreated. Using @FragmentScope made my life harder as it introduced some other bugs.
You can look here to learn more about scoping and the functionality of dagger-hilt
Solution 2:[2]
To get instance from hilt directly you should use EntryPoint annotation:
example code can be found here: https://developer.android.com/codelabs/android-hilt#10
Steps are as follows:
Declare in your non-Hilt aware class an interface implementing a method returning interface of instance you want to retrieve from Hilt.
Annotate this interface with
@InstallIn(SingletonComponent::class) @EntryPoint
assuming your instance is a singleton, so it would look as follows:
class MyAnyKindOfClass {
@InstallIn(SingletonComponent::class)
@EntryPoint
interface MyObjectEntryPoint{
fun getMyObject(): MyObject;
}
fun getMyObject(): MyObject {
val hiltEntryPoint = EntryPointAccessors.fromApplication(
appContext, // You need to provid ApplicationContext
MyObjectEntryPoint::class.java)
return hiltEntryPoint.getMyObject()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew |
| Solution 2 | marcinj |
