Dagger2 one module for two different areas

In my application, I have ApplicationScope that provides me with things like context and general privileges. 2 subcomponents, LoggedInComponent and LoggedOutComponent. These 2 subcomponents have other subcomponents that are less relevant to this problem.

I have a NetworkModule that creates my modification instance. Both subcomponents need a NetworkModule, but the modification may change during login, because the base url and other settings may change.

I was wondering which approach is better to take: 1. Give the LoggedIn and LoggedOut and NetworkModule subcomponents the same scope so that both subcomponents can use this module. Feels a bit hacked and misused areas. 2. Place the network module in the AppComponent using ApplicationScope. Also, the wrong use of the area, because the network module is recreated, so it cannot have the same volume, and also every rest will lead to the recreation of the AppComponent and its subcomponents.

What would you do? maybe there is a better solution?

+1
source share
1 answer

, LoggedInComponent LoggedOutComponent , , LoggedInComponent LoggedOutComponent, NetworkModule . , AppComponent. , AppComponent ApplicationScope: AppComponent, .

, NetworkModule AppComponent, NetworkModule. , (. " " Dagger), , , .

, NetworkComponent, NetworkManager, (ApplicationScope). NetworkComponent.

@Module(subcomponents={NetworkComponent.class})
public abstract class ApplicationModule {
  /** Unscoped. Fetch this fresh from NetworkComponentHolder each time. */
  @Provides Retrofit provideRetrofit(NetworkManager manager) {
    return manager.getNetworkComponent().getRetrofit();
  }
}

@ApplicationScope public class NetworkManager {
  private final Provider<NetworkComponent.Builder> builderProvider;
  private NetworkComponent currentComponent;

  @Inject public NetworkComponentHolder(
      Provider<NetworkComponent.Builder> builderProvider) {
    this.builderProvider = builderProvider;
    currentComponent = builderProvider.get()
        .withNetworkModule(getDefault())
        .build();
  }

  public void updateSettings(String baseUrl) {
    currentComponent = builderProvider.get()
        .withNetworkModule(new NetworkModule(baseUrl))
        .build();
  }

  public NetworkComponent getNetworkComponent() {
    return currentComponent;
  }
}

AppComponent, LoggedInComponent LoggedOutComponent Retrofit ( Provider<Retrofit>), . , URL-, NetworkManager, updateSettings, Retrofit . ( , , Retrofit , , , .)

p.s. NetworkModule , NetworkModule ApplicationComponent NetworkManager Retrofit .. , provideRetrofit, , .

+1

Source: https://habr.com/ru/post/1673700/


All Articles