Raf*_*yan 7 java android dependency-injection dagger dagger-2
假设这里已经说过,开发人员有责任保留组件实例以实现自己的范围逻辑(因为范围方法将为给定组件返回相同的实例).
通过活动生命周期保持此组件引用的干净方法是什么?
示例:您正在实施MVP模式,因此您需要在Activity中使用Presenter.此演示者可以执行网络操作来下载项目.当设备旋转时,您的Activity将被销毁并重新创建,但您希望保持网络运行并返回预旋转演示者.
在为Presenter提供自定义PerActivity范围的组件范围是解决方案,因此您必须通过此循环保持Component实例,以便在首次启动Activity时注入相同的Presenter实例.
我们怎么处理这个?我想到了一种组件缓存(如HashMap?),它可以由Application类中的Application Component提供.
您可以看到ribot/android-boilerplate展示应用程序的实现。static Map<Long, ConfigPersistentComponent>他们选择的解决方案是在 内部建立一个BaseActivity,所有活动都从该内部扩展。
public class BaseActivity extends AppCompatActivity {
private static final AtomicLong NEXT_ID = new AtomicLong(0);
private static final Map<Long, ConfigPersistentComponent> sComponentsMap = new HashMap<>();
private ActivityComponent mActivityComponent;
private long mActivityId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the ActivityComponent and reuses cached ConfigPersistentComponent if this is
// being called after a configuration change.
mActivityId = savedInstanceState != null ?
savedInstanceState.getLong(KEY_ACTIVITY_ID) : NEXT_ID.getAndIncrement();
ConfigPersistentComponent configPersistentComponent;
if (!sComponentsMap.containsKey(mActivityId)) {
// Creating new component
configPersistentComponent = DaggerConfigPersistentComponent.builder()
.applicationComponent(BoilerplateApplication.get(this).getComponent())
.build();
sComponentsMap.put(mActivityId, configPersistentComponent);
} else {
// Reusing component
configPersistentComponent = sComponentsMap.get(mActivityId);
}
mActivityComponent = configPersistentComponent.activityComponent(new ActivityModule(this));
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(KEY_ACTIVITY_ID, mActivityId);
}
@Override
protected void onDestroy() {
if (!isChangingConfigurations()) {
// Activity is finishing, removing the component
sComponentsMap.remove(mActivityId);
}
super.onDestroy();
}
...
}
Run Code Online (Sandbox Code Playgroud)