Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger2 vs Application class in android

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?

like image 989
sasikumar Avatar asked May 16 '26 05:05

sasikumar


1 Answers

As we know Dagger is Dependency Injection.

Brief which makes the dagger unique:

Benefits:

  1. 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.

  2. We can use the dagger to reuse the object through object graph.

  3. We can distribute the dependency like for
    • Project level
    • App level
    • Module level(Like : Home,Account in the app)
  4. 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.

  5. Can inject Class,Object,Constructor.

like image 125
Harshad07 Avatar answered May 18 '26 20:05

Harshad07