gpt4 book ai didi

android - android中的MVVM,在不破坏模式的情况下访问assetManager

转载 作者:行者123 更新时间:2023-11-29 18:35:35 25 4
gpt4 key购买 nike

我在 Assets 文件夹中有一个 JSON 文件,DataManager(存储库)类需要它,因此 Assets 管理器(和上下文)应该可以访问 Assets 。

问题是,根据最佳实践,Android 上下文或 Android 特定代码不应传递到数据层(ViewModel-Repo-Model),因为编写单元测试等很容易,而且 View 不应与数据交互直接分层。

我最终提供了使用列表并将其注入(inject)存储库。

这是正确的做法吗?

-谢谢

P.S: 我的模块类提供了列表

@Module
public class UtilModule {

@Provides
@JsonScope
JsonUtil provideJsonUtil(AssetManager assetManager){
return new JsonUtil(assetManager);
}

@Provides
@JsonScope
String provideJson(JsonUtil util){
return util.getJson();
}

@Provides
@JsonScope
Type provideType(){
return new TypeToken<List<Data>>() {}.getType();
}
@Provides
@JsonScope
DataManager provideDataManager (Gson gson, Type type,String json) {
return new DataManager (gson.fromJson(json, type));
}
}

最佳答案

ViewModel 和/或 Repository 访问 Application 并不违反 MVVM。直接访问上下文,这就是访问 AssetsManager 所需的全部内容。调用 Application.getAssets() 是可以的,因为 ViewModel 不使用任何特定的 Activity 的上下文。

例如,您可以使用 Google 提供的 AndroidViewModel子类而不是父类(super class) ViewModel . AndroidViewModel 在其构造函数中获取一个 Application(ViewModelProviders 将为您注入(inject))。您可以在其构造函数中将您的 Application 传递给您的 Repository

或者,您可以使用 Dagger依赖注入(inject)将 Application 直接注入(inject)您的 Repository。 (注入(inject) Application 上下文有点棘手。请参阅 Dagger 2 injecting Android Contextthis issue filed on the Danger github repo。)如果你想让它变得非常光滑,你可以为 AssetManager 配置一个提供者并将其直接注入(inject)您的 Repository

最后,如果您正在使用 Room,并且您想要的只是使用存储在 Assets 中的预配置数据库预填充 Room 数据库,您可以按照此处的说明进行操作:How to use Room Persistence Library with pre-populated database?

关于android - android中的MVVM,在不破坏模式的情况下访问assetManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503406/

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