gpt4 book ai didi

java - 在方向改变时处理 Dagger 组件

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:14:59 24 4
gpt4 key购买 nike

假设已经说过here ,开发人员有责任保留组件实例以实现他们自己的作用域逻辑(因为作用域方法将为给定组件返回相同的实例)。

在整个 Activity 生命周期中保持此组件引用的简洁方法是什么?

示例:您正在实现 MVP 模式,因此您的 Activity 中需要一个 Presenter。此 Presenter 可以执行网络操作以下载项目。当设备旋转时,您的 Activity 将被销毁并重新创建,但您希望继续进行网络操作并只取回旋转前的演示者。

为 Presenter 提供自定义 PerActivity 范围的 Component 范围是解决方案,因此您必须通过此轮换保持 Component 实例,以便注入(inject)与第一次启动 Activity 相同的 Presenter 实例。

我们该如何应对?我想到了一种组件缓存(如 HashMap ?),它可以由应用程序类中的应用程序组件提供。

最佳答案

可以看到ribot/android-boilerplate的实现展示应用程序。他们选择的解决方案是拥有一个 static Map<Long, ConfigPersistentComponent> BaseActivity 里面,所有 Activity 都从中延伸。

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();
}

...

}

关于java - 在方向改变时处理 Dagger 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38766352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com