0

Lets say i have a Singleton Class which is injected using dagger

@Singleton
class SingletonClass {

    @Inject
    lateinit var newInstanceEveryTime: NewInstanceEveryTime

    fun getNewInstance(): NewInstanceEveryTime {
        return newInstanceEveryTime
    }
}

whenever i call the method getNewInstance() using SingletonClass.getNewInstance(), i need to get the new instance every time, but i know that it will not create the instance every time, Can anyone help me how can i achieve this from singleton class using dagger.

Stack
  • 1,164
  • 1
  • 13
  • 26
  • I still don't get what you are asking? And why would you have such a method in the first place when you have Dagger? Just inject the other class where you need it with the right scope or no scope at all. – Yavor Mitev Oct 18 '19 at 07:54
  • Just to clarify. Here what you have now is only one istance of SingletonClass, wich will will be injected only once with NewInstanceEveryTime, and from then on you will return the same instance again and again. If you want new instance each time just do: fun getNewInstance() = NewInstanceEveryTime(), but again it does not make sense for me. – Yavor Mitev Oct 18 '19 at 07:58
  • Does this answer your question? [Dagger: What if I \*WANT\* a new instance every time?](https://stackoverflow.com/questions/53763934/dagger-what-if-i-want-a-new-instance-every-time) – Hassan Ibraheem Jan 18 '20 at 06:27

1 Answers1

-1

If you create like this the class it will be injected as a new instance every time when it is needed:

class NewInstanceEveryTime @Inject constructor() {}

or you can do like this:

@Singleton
class SingletonClass {

    fun getNewInstance() = NewInstanceEveryTime()
}

But what is your use case? Why would you need such factory method?

Yavor Mitev
  • 1,363
  • 1
  • 10
  • 22
  • Here for NewInstanceEveryTime, you are creating the instance manually not by dagger, if you want to inject some other instance in NewInstanceEveryTime, dagger will throw error, since the NewInstanceEveryTime is not injected by dagger – Stack Oct 18 '19 at 10:50
  • @Stack your comment just does not make sense. First of all I have said in the comment and in the question that I just don't understand what is the point of this at all. Second of all the above code is working fine, because I said OR: if there is only constructror injection with Inject annotation, I will not create instance on my own. All good. If there is only instance created on my own, no Inject annotation, Dagger will not know that NewInstanceEveryTime have existed at all so no problem there also. – Yavor Mitev Oct 18 '19 at 10:56