I make manual di using class AppContainer
internal class AppContainer private constructor(context: Context) {
companion object {
private var instance: AppContainer? = null
fun getInstance(context: Context): AppContainer {
if (instance == null) {
instance = AppContainer(context.applicationContext)
}
return instance!!
}
}
val resourceProvider: ResourceProvider by lazy { provideResourceProvider(context = context.applicationContext) }
..............
}
In all creation places I use app context, but it's cause memory leak. Why? Can I fix it without Kotin/Dagger?
CodePudding user response:
I has found reason. ViewHolder context
companion object {
fun onCreate(
parent: ViewGroup,
playerController: PlayerController,
playerActions: PlayerActions
): VideoViewHolder {
return VideoViewHolder(
VideoItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
playerController,
playerActions
)
}
}
I replaced parent.context to parent.context.applicationContext
CodePudding user response:
By annotating context with @ApplicationContext provided by Hilt, we don't need to create a provider for the application context.
Sample usage
@Module
@InstallIn(SingletonComponent::class)
class ProductionModule {
@Singleton
@Provides
fun provideAppDatabase(@ApplicationContext appContext: Context): AppDatabase {
return Room
.databaseBuilder(appContext, AppDatabase::class.java, AppDatabase.DB_NAME)
.build()
}
}
The scope of the AppContainer is only within your onCreate function, so once onCreate executed, your "your object" object is no longer needed and subject to garbage collection.