Reputation: 1873
I Have Separate Class I want to put inject in its body, but it's not allowed to make it A EntryPoint Because it's not a Fragment or Activity so Injection must be in Fragment or Activity
Upvotes: 2
Views: 1828
Reputation: 871
so Injection must be in Fragment or Activity
This is incorrect, Injection can be done anywhere as long as the EntryPoint
whether it was a Fragment or Activity is annotated with @AndroidEntryPoint
.
For example,
If you have Class A that is a member of the MainActivity, and ClassB that is a dependency of Class A. So as long as MainActivity
is annotated with @AndroidEntryPoint
you can Inject ClassA into MainActivity and ClassB into ClassA.
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var classA: ClassA
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
classA.test()
}
}
class ClassA @Inject constructor(){
@Inject
lateinit var classB: ClassB
fun test() = classB.test()
}
class ClassB @Inject constructor(){
fun test() = println("Hello World")
}
Output : Hello World
Upvotes: 2