简体   繁体   中英

Dagger 2 lazy initialize map entries

I have a Dagger module and component defined as below. I want to create the resources in the module only when they are being fetched from the map and not when the service comes up. I played around using Lazy but not sure how to achieve this.

@Module
public abstract class ExpensiveObjectModule {

    @Singleton
    @Provides
    @IntoMap
    @UniqueKey(Key.A)
    static ExpensiveObject provideKeyAExpensiveObject() {
        return new ExpensiveObject(Key.A);
    }

    @Singleton
    @Provides
    @IntoMap
    @UniqueKey(Key.B)
    static ExpensiveObject provideKeyBExpensiveObject() {
        return new ExpensiveObject(Key.B);
    }
}
@Singleton
@Component (modules = {
        ExpensiveObjectModule.class
})
public interface HandlerComponent {
    Map<Key, ExpensiveObject> getExpensiveObjectByKey();

}
handlerComponent.getExpensiveObjectByKey().get(key);

Whenever you can inject A you can also inject Provider<A> , so instead of having a Map<K, A> you can have a Map<K, Provider<A>> . The same would probably work with Lazy, but a Provider will respect whatever scope something has, while Lazy would always cache it.

So you could just return the map like this:

Map<Key, Provider<ExpensiveObject>> getExpensiveObjectByKey();

A minimal example (but in Kotlin) looks like this:

@MustBeDocumented
@Target(
    AnnotationTarget.FUNCTION,
    AnnotationTarget.PROPERTY_GETTER,
    AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class Key(val value: String)

@Module
object ModFoo {

    @Provides
    @IntoMap
    @Key("foo")
    fun foo(): Any = "Foo"

    @Provides
    @IntoMap
    @Key("bar")
    fun bar(): Any = 3
}

@Component(modules = [ModFoo::class])
interface Foo {
    val foo: Map<String, Any>
    val fooProviders: Map<String, Provider<Any>>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM