Should I use @Singleton, object or both with Dagger2 and Kotlin?

I'm doing an app using Kotlin and Dagger2, trying to follow the MVVM pattern, but I'm in a dilemma, should I use @Singleton, object or both? And why? Let's say I have a RepositoryMovies class and I want to get the same instance every time, according to my research you can do this as follows:

@Singleton (Dagger2 way)

@Singleton
class RepositoryMovies {
    TODO()
}

Object (Kotlin way)

object RepositoryMovies {
    TODO()
}

Both

@Singleton
object RepositoryMovies {
    TODO()
}

And don't get me started with singletons in Kotlin following the "Java-Way". I'd appreciate your help. Thanks so much.

Upvotes: 2

Views: 3086

Answers (2)

U wan
U wan

Reputation: 61

A Singleton as a Design pattern allows only one instance of a class.

A (Kotlin) object is a static class, hence it's the only instance of the class. So this fulfills/enforces the singleton pattern.

A Dagger Singleton (with the javax @Singleton annotation) is the dagger implementation of the Singleton pattern. It ensures the same instance of a class in the current Dagger Component.

Note that you would receive a different instances for a different Dagger Component. You could also hold 2 instances of a Dagger Component which would return different instances of your Singleton.

Upvotes: 1

mightyWOZ
mightyWOZ

Reputation: 8315

Injecting an object doesn't make much sense, since in kotlin object is used to simulate java's utility classes, such as java's Arrays or Collections classes. One defining characteristic of such classes is that, they are not associated with any specific class in your project, they can be required and used anywhere.

On the other hand in most practical situations a repository will be associated with a specific class. for example you may only want to inject a UserRepository in a UserViewModel, because that is the only place where you need to access user's information.

As for the object and @Singleton, object is by definition a singleton, so marking it with @Singleton is redundant and doesn't accomplish anything until you make it injectable by means of a @Provides function. where you have to specify, how dagger can create instances of this class?

In your first example marking a class @Singleton doesn't do anything, unless it is injectable. as the docs state.

Singletons and Scoped Bindings

Annotate an @Provides method or injectable class with @Singleton. The graph will use a single instance of the value for all of its clients.

Upvotes: 3

Related Questions