android10 / Android-CleanArchitecture

This is a sample app that is part of a series of blog posts I have written about how to architect an android application using Uncle Bob's clean architecture approach.
Apache License 2.0
15.52k stars 3.32k forks source link

I don't know why does Dagger work in this way? #240

Open Johnny850807 opened 7 years ago

Johnny850807 commented 7 years ago

Here exposing several dependencies such like those parameters jobExecutor, uiThread... But to my knowledge, there should be somewhere else provides the dependency here needs, otherwise error occurs. I can't find any module provides them, could someone please tell me why does this example work?


@Module
public class ApplicationModule {
  private final AndroidApplication application;

  public ApplicationModule(AndroidApplication application) {
    this.application = application;
  }

  @Provides @Singleton Context provideApplicationContext() {
    return this.application;
  }

  @Provides @Singleton ThreadExecutor provideThreadExecutor(JobExecutor jobExecutor) {
    return jobExecutor;
  }

  @Provides @Singleton PostExecutionThread providePostExecutionThread(UIThread uiThread) {
    return uiThread;
  }

  @Provides @Singleton UserCache provideUserCache(UserCacheImpl userCache) {
    return userCache;
  }

  @Provides @Singleton UserRepository provideUserRepository(UserDataRepository userDataRepository) {
    return userDataRepository;
  }
}
guitoun3 commented 7 years ago

Those dependencies are automatically provided for you because they are constructor annotated.

For example provideThreadExecutor requires a JobExecutor. If you look at the class JobExecutor you'll see that the class is annotated with a @Singleton and the constructor is annotated with an @Inject.

This way you don't have to provide it manually on your module.

Johnny850807 commented 7 years ago

Well, I think I almost understand, So the reason of why the author didn't have to write a provide method to Presenter and UseCase is that all of the them are written as a concrete subclass.

In order to keep the Dagger clean, we don't make a polymorphism to presenters or usecases, and this is unnecessary right?

guitoun3 commented 7 years ago

That's right at least that's how I understand it!

For example JobExecutor is an implementation of ThreadExecutor. In the code JobExecutor is used because you don't care about implementation. You let Dagger provide it for you.

But concerning Presenter you actually need the implementation. Because a Presenter is tightly coupled to a View. An interface is used only for testing purpose to allow using mock and easily test each component separately.