Suresh Sharma
Suresh Sharma

Reputation: 1844

Shall we pass injected object in another class

I am just playing around the Dagger2 for DI implementation in Android.

My query is nothing about the problem that I am facing but just a knowledge gaining.

I intend to inject a class in my Activity and want to pass it to my ViewModel class. Is this a good approach to follow the best practices in Dependency Injection? Will it arise any issue related to leak or performance.

Upvotes: 0

Views: 604

Answers (1)

Jasurbek
Jasurbek

Reputation: 2966

No, it is not. You should use scope and make injection possible inside your ViewModel.

What you are trying to do is against the idea behind dependency injection. Dependency injection libs create a dependency tree based on your Models then allow you to use this tree in your application.

  • If you are initializing each an every time, you do not know what is the current state of your object.
  • Most of the time you need one instance in some scope like inside activities, or fragments ... this problem can be solved by Dagger2 easily

Scope ensures you have only one instance inside the given scope.

Upvotes: 1

Related Questions