简体   繁体   中英

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.

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?

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)? If so, you could put them eg in gradle.properties and save them as BuildConfig Field

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. In your Main activity create one object with the creds and then just send this object across the application as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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