stefano capra
stefano capra

Reputation: 159

Dagger2: return not singleton object from singleton component

how can I return not singleton objects from a @Singleton component?

For example I have:

ApplicationComponent.kt

@Singleton
@Component(modules = [ApplicationModule::class])
interface ApplicationComponent() {
    fun database(): Database
    fun model(): Model
}

Model.kt

class Model @Inject constructor()

What I want is to return a different instance of Model every time, conversely to Database which will be a singleton, and been provided by ApplicationModule.kt

Upvotes: 1

Views: 218

Answers (1)

tynn
tynn

Reputation: 39873

If you provide your Model as

@Singleton
class Model @Inject constructor()

or as

@Provides
@Singleton
fun provideModel() = Model()

it will be a singleton.

If you don't annotate any provider with @Singleton, @Reusable or any other scope, you will always create a new instance.

Upvotes: 2

Related Questions