简体   繁体   English

MVVM 在多个存储库中重复代码

[英]MVVM duplicated code in multiple Repositories

I have multiple repositories who needs some credentials to work with an external service.我有多个存储库,需要一些凭据才能使用外部服务。 Those credentials are stored in the Shared Preferences of my app and I successfully load it in every repository.这些凭据存储在我的应用程序的共享首选项中,我成功地将它加载到每个存储库中。

To specify those credentials are used in the SOAP header request and they are provided by the user.指定在 SOAP 标头请求中使用的那些凭据,它们由用户提供。

With the current solution I load those creds in the activities and then pass down to the repository through a method in the viewmodels.使用当前的解决方案,我将这些凭据加载到活动中,然后通过视图模型中的方法传递到存储库。 This approch generates a lot of duplicated code, since for each activity where I need those creds I repeat the whole process.这种方法会生成大量重复的代码,因为对于我需要这些凭据的每个活动,我都会重复整个过程。

Is there any better solution that will follow the MVVM best practices and avoid duplicate code?有没有更好的解决方案可以遵循 MVVM 最佳实践并避免重复代码?

Can you provide more context?你能提供更多的上下文吗?

In my opinion there is no general answer without knowing more about your application.在我看来,如果不了解有关您的应用程序的更多信息,就没有通用的答案。 Does these repositories use the same service (eg network service?).这些存储库是否使用相同的服务(例如网络服务?)。 If so, you could add them as an custom Interceptor.如果是这样,您可以将它们添加为自定义拦截器。

You could inject them in an abstraction layer behind the repositories.您可以将它们注入存储库后面的抽象层中。

Why do you store the credentials in shared preferences?为什么将凭据存储在共享首选项中? Are they static (like network api keys you got from the api)?它们是静态的(比如你从 api 获得的网络 api 密钥)? If so, you could put them eg in gradle.properties and save them as BuildConfig Field如果是这样,您可以将它们放在例如 gradle.properties 中并将它们保存为 BuildConfig 字段

To avoid redundant code, one thing you can do is write that code in an utility class and use that in your repositories.为了避免冗余代码,您可以做的一件事是在实用程序类中编写该代码并在您的存储库中使用它。 Hope it helps!希望能帮助到你! :) :)

You can write one POJO class which will hold the credentials.您可以编写一个 POJO 类来保存凭据。 In your Main activity create one object with the creds and then just send this object across the application as needed.在您的 Main 活动中,使用凭证创建一个对象,然后根据需要在整个应用程序中发送该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM