【发布时间】:2015-07-07 12:53:45
【问题描述】:
我正在 GitHub 上阅读 Dagger2 Component Scopes Test 的源代码,并且我看到了为名为 @ActivityScope 的活动定义的“自定义范围”,但我在其他项目中看到了它,包括 4 模块 @987654322 @ 有其 @PerActivity 范围。
但从字面上看,@ActivityScope 注解的代码如下:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
/**
* Created by joesteele on 2/15/15.
*/
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {
}
它在模块中“神奇地”可用:
@Module
public class ActivityModule {
@Provides @ActivityScope Picasso providePicasso(ComponentTest app, OkHttpClient client) {
return new Picasso.Builder(app)
.downloader(new OkHttpDownloader(client))
.listener(new Picasso.Listener() {
@Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
Log.e("Picasso", "Failed to load image: " + uri.toString(), e);
}
})
.build();
}
}
或者CleanArchitecture例子:
@Scope
@Retention(RUNTIME)
public @interface PerActivity {}
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
//Exposed to sub-graphs.
Activity activity();
}
@Module
public class ActivityModule {
private final Activity activity;
public ActivityModule(Activity activity) {
this.activity = activity;
}
/**
* Expose the activity to dependents in the graph.
*/
@Provides @PerActivity Activity activity() {
return this.activity;
}
}
我可以清楚地看到这与 JSR-330 自定义范围有关,但我真的不明白这里到底发生了什么,以便此代码启用给定的模块和/ 或给定模块提供的内容取决于实际的 Activity 生命周期,并且仅存在一个实例,但前提是该给定活动处于活动状态。
文档是这样说的:
Scope
Dagger 1 only supported a single scope: @Singleton.
Dagger 2 allows users to any well-formed scope annotation.
The Component docs describe the details of
how to properly apply scope to a component.
它说要查看Component docs page,但这给了我404。我也看到了this,但是...
我是否可以寻求一些帮助以澄清为什么指定此自定义范围会神奇地使 Activity-level scopes 正常工作?
(答案是,子作用域可以从其超作用域接收依赖,只要组件存在,子作用域就存在。而且你需要在你的模块上指定作用域,你需要指定你的组件对子作用域的依赖关系一个超级作用域。)
【问题讨论】:
-
这是组件文档页面的正确链接,供任何阅读此内容的人使用:google.github.io/dagger/api/2.0/dagger/Component.html
标签: android android-activity scope dagger-2