[英]Dagger 2 lazy initialize map entries
I have a Dagger module and component defined as below.我有一个 Dagger 模块和组件定义如下。 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.
我玩过使用 Lazy 但不知道如何实现这一点。
@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>>
.每当您可以注入
A
您也可以注入Provider<A>
,因此您可以拥有Map<K, Provider<A>>
,而不是Map<K, A>
。 The same would probably work with Lazy, but a Provider will respect whatever scope something has, while Lazy would always cache it. Lazy 可能也是如此,但是 Provider 会尊重某物的任何作用域,而 Lazy 总是会缓存它。
So you could just return the map like this:所以你可以像这样返回地图:
Map<Key, Provider<ExpensiveObject>> getExpensiveObjectByKey();
A minimal example (but in Kotlin) looks like this:一个最小的例子(但在 Kotlin 中)如下所示:
@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>>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.