确保存储库在android中是单例的

问题描述 投票:0回答:1

我已经开始在我的Kotlin android应用中使用匕首。我想确保存储库只初始化一次,所以我为存储库添加了@Singleton作用域,这是否足够,或者是否有任何设计优势可以在纯Kotlin中执行一些其他步骤以使类为Singleton?

@Module
abstract class RepositoryModule{

    @Binds
    @Singleton
    abstract fun provideRepository(someRepo : SomeRepo): Repository
}



@Singleton
@Component(modules = [
    AndroidSupportInjectionModule::class,
    ActivityBindingModule::class,
    RepositoryModule::class,
])

interface AppComponent : AndroidInjector<MyApplication>


class SomeRepo @Inject constructor (
     service : Service ,
     anotherService : Service 
) : Repository{
android kotlin singleton repository dagger
1个回答
0
投票

简短的答案是,如果您在同一Somerepo中使用此Component,它将始终是同一实例,如果尝试从另一个Component提供它,它将创建另一个实例,并且在整个生命周期内都保持活动状态的组件。

您总是可以放置一个断点并查看实例并进行比较。

© www.soinside.com 2019 - 2024. All rights reserved.