Why do we use Android support injection in our fragment?
I think you are talking about Dagger 2[1] and Dependency Injection[2].
Dependency injection is a design pattern based on the principle of Inversion of Control[3]. It states that a class should receive all its dependencies from outside and should not create dependencies itself.
For example:
Let say you have a class A
- class A {
- //constructor
- A() {}
- }
And another class B
- class B {
- private A a;
- //constructor
- B() {
- a = new A();
- }
- }
The problem with definition of class B is that it creates an object of class A inside its constructor. This makes testing of class B difficult as you don’t know how to provide instance of class A
A better way to write class B would be
- class B {
- private A a;
- //constructor
- B(A a) {
- this.a = a;
- }
- }
Now, to mock class B you have to mock class A and provide it externally. This is called constructor injection.
You can do the same injection while creating your Fragment. There is absolutely nothing wrong in it. But, Android System sometimes creates Fragment instances on its own (during device rotation and configuration changes, this is also the reason why we need to provide empty constructor in fragment). Hence, we need to inject dependencies some other way.
We use field injection for it. As under,
- class GameFragment extends Fragment {
- @Inject GameService gameService;
- @Inject GameViewmodel gameViewmodel;
- //empty constructor for android system use
- public GameFragment() {}
- @Override
- public void onCreate(Bundle savedInstanceState) {
- AndroidSupportInjection.inject(this);
- super.onCreate(savedInstanceState);
- }
- }
Please see on line 10 above. This is where dependencies are injected. Also, note that Dagger cannot inject private fields and hence there is no private modifier with @Inject.
I hope this helps.
Footnotes
[1] Practical guide to Dagger 2[2] Dependency injection - Wikipedia[3] Inversion of control - Wikipedia