https://kotlinlang.org logo
#dagger
Title
# dagger
s

Sinan Gunes

02/15/2021, 12:43 PM
What is the proper way to have a singleton while using assisted injection. I mean same
@Assisted
parameter should return same object.
w

wasyl

02/15/2021, 12:44 PM
You pass assisted parameters yourself, so you control their lifecycle
s

Sinan Gunes

02/15/2021, 12:47 PM
using
AssistedFactory
or hand made?
w

wasyl

02/15/2021, 12:49 PM
I’m not sure I understand what you mean, can you give an example of what you want to achieve?
s

Sinan Gunes

02/15/2021, 12:51 PM
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

wasyl

02/15/2021, 12:53 PM
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

Sinan Gunes

02/15/2021, 12:54 PM
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

wasyl

02/15/2021, 12:56 PM
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

Sinan Gunes

02/15/2021, 12:58 PM
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

wasyl

02/15/2021, 1:04 PM
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

Sinan Gunes

02/15/2021, 1:09 PM
sounds good. better than I originally thought. thanks @wasyl 👍🏻
👍 1