Spekus
Spekus

Reputation: 1

Ensuring repository is singleton in android

I have started using dagger for my kotlin android app. I want to ensure that repository would be initialized only once, so I have added @Singleton scope for repository.Is this enough or are there any design benefits to do some additional steps in plain kotlin to make the class is 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{

Upvotes: 0

Views: 731

Answers (1)

Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20646

Short answer is, if you use this Somerepo in the same Component it will always be the same instance, if you try to provide from another Component it will create another instance and is only kept alive for the lifetime of the component.

You can always put a breakpoint and see the instance and compare it.

Upvotes: 1

Related Questions