By this simple example
public class MyApp extends Application {
private static MyApp app;
private ImageDownloaderComponent imageDownloaderComponent; // dagger2
ImageDownloader imageDownloader;
@Override
public void onCreate() {
super.onCreate();
app = this;
imageDownloaderComponent = DaggerImageDownloaderComponent.builder().imageDownloaderModule(new ImageDownloaderModule(this)).build();
imageDownloader=new ImageDownloader(this);
}
public static MyApp app(){
return app;
}
public ImageDownloaderComponent getImageDownloaderComponent(){
return this.imageDownloaderComponent;
}
}
using Dagger2
public class MainActivity extends AppCompatActivity {
@Inject ImageDownloader downloader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyApp.app().getImageDownloaderComponent().inject(this);
ImageView imageView = findViewById(R.id.main_image);
downloader.toImageView(imageView, "https://..../fruits.png");
} }
without dagger2
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageView imageView = findViewById(R.id.main_image);
MyApp.app().imageDownloader.toImageView(imageView, "https://---/fruits.png");
}
}
Both the case activity is working fine. my question why we need dagger2 even the same task performed by the application class? how the way its effective? i google it ,i got its easy for testing apart from any benefits there?? which activity is good in above examples? why?
As we know Dagger is Dependency Injection.
Brief which makes the dagger unique:
Benefits:
If we are using dagger in very small projects/tasks like you given then dagger doesn't deserve for that.It would be more efficient it is used in intermediate,long applications. Because it help us to avoid unwanted object creation in the code.
We can use the dagger to reuse the object through object graph.
We can define custom scope ,also there are some already defined scopes like Singleton , there are good concepts in dagger like component dependency & sub component.
Can inject Class,Object,Constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With