Is it possible to selectively install modules for components in dagger 2?

Caused by: java.lang.IllegalStateException: analyticsModule must be set

I am creating a library that uses template style initialization. The user can selectively install modules for the project using this library. It uses Dagger 2 for DI.

But Dagger 2 does not seem to provide additional modules. Can't just ignore modules?

+4
source share
1 answer

You might want to consider using Multibindings, which allows users to add additional dependencies to Set<T>or Map<K,V>. Here is an example:

interface Plugin {
    void install(Application application);
}

@Component({ModuleA.class, ModuleB.class})
interface PluginComponent {
    Set<Plugin> plugins();
}

@Module
class ModuleA {
    @Provides(type = SET) Plugin providFooPlugin() {
        return new FooPlugin();
    }
}

@Module
class ModuleB {
    @Provides(type = SET) Plugin providBarPlugin() {
        return new BarPlugin();
    }
}

, . - @Provides(type = SET_VALUES) , , Collections.emptySet(). :

interface Plugin {
    void install(Application application);
}

@Component({ModuleA.class, ModuleB.class})
interface PluginComponent {
    Set<Plugin> plugins();
}

@Module
class ModuleA {
    private final Set<Plugin> plugins;

    ModuleA(Set<Plugin> plugins) {
        this.plugins = plugins;
    }

    @Provides(type = SET_VALUES) Plugin providFooPlugins() {
        return plugins;
    }
}

@Module
class ModuleB {
    @Provides(type = SET) Plugin providBarPlugin() {
        return new BarPlugin();
    }
}

:

DaggerPluginComponent.builder()
    .moduleA(new ModuleA(Collections.emptySet())
    .build();

, :

Set<Plugin> plugins = new HashSet<>();
plugins.add(new AwesomePlugin());
plugins.add(new BoringPlugin());
DaggerPluginComponent.builder()
    .moduleA(new ModuleA(plugins)
    .build();
+6

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


All Articles