What is the proper way to have a singleton while u...
# dagger
s
What is the proper way to have a singleton while using assisted injection. I mean same
@Assisted
parameter should return same object.
w
You pass assisted parameters yourself, so you control their lifecycle
s
using
AssistedFactory
or hand made?
w
I’m not sure I understand what you mean, can you give an example of what you want to achieve?
s
basically I am trying to create a Retrofit WebService, but Base Url is provided runtime.
simply this worked, however it returns a new WebService everytime:
Copy code
class ChatRepositoryImpl @AssistedInject constructor(@Assisted("baseUrl") baseUrl: String)
    : ChatRepository by buildRetrofit(baseUrl).create(ChatRepository::class.java) {
}


@AssistedFactory
interface ChatRepoFactory {
    @Singleton
    fun create(@Assisted("baseUrl") baseUrl: String): ChatRepositoryImpl
}
w
If I understand correctly, your
@Singleton
is in wrong place — it should be placed at
class ChatRepositoryImpl
, just like you would with a regular
@Inject
s
you can ignore this
@Singleton
there, because it is not working. Also Dagger does not allow me to put above
ChatRepositoryImpl
. :
Copy code
Assisted Injection cannot be scoped
w
Ah right. In that case you need to scope the class in which you’re creating the repository.
It’s not possible to return the same instance from a factory because what should Dagger do if you try to do something like this:
Copy code
val instance1 = factory.create(baseUrl = "foo")
val instance2 = factory.create(baseUrl = "bar")
?
s
I would expect to return different instances.
my case seems an edge one. I will cache instances somewhere if there is no other way.
w
I would expect to return different instances.
If you want to return the same instances for the same `baseUrl`s then you just need to do that manually, Dagger won’t do that for you. So you’d need a
@Singleton
-scoped class which will internally hold
ChatRepoFactory
and cache the returned instances for the same urls
s
sounds good. better than I originally thought. thanks @wasyl 👍🏻
👍 1