简体   繁体   English

存储库可以是 mvvm android 中的 singleton?

[英]Repository can be singleton in mvvm android?

I don't understand few things about repository in mvvm, also have seen multiple blogs and code templates.我不太了解 mvvm 中的存储库,也看过多个博客和代码模板。 Every one of them doesn't match with other.他们每个人都与其他人不匹配。 So所以

  1. Why there is needs to have multiple Repositories classes?为什么需要有多个存储库类? Why single repository shouldn't handle all the data IN OUT for the app?为什么单个存储库不应处理应用程序的所有输入输出数据?

  2. Why Repository shouldn't be a SINGLETON class in project?为什么存储库不应该是项目中的 SINGLETON class?

  3. What a repository('s method) should provide to viewmodel Result(Sealed class) or actual response from a api like list(or error)?存储库(的方法)应该向 viewmodel 结果(密封类)或 api 之类的列表(或错误)的实际响应提供什么?

  4. SharedPrefrences should be handled by Repository as well or not? SharedPrefrences 是否也应该由 Repository 处理? if no why如果没有为什么

    I believe Repository should be that part of your code which should process all the data from multiple source whether be database or.network or sharedprefs.我相信 Repository 应该是您的代码的一部分,它应该处理来自多个来源的所有数据,无论是数据库还是.network 还是 sharedprefs。 So what do you think?所以你怎么看?

  1. Purpose of repository is not only to manage requests/response but also provide a layer to keep responsibilities separated.存储库的目的不仅是管理请求/响应,还提供一个层来保持职责分离。 If you have 2 modules (let's say Login and Registration), it is much better to keep repositories separated to keep things clean and simple rather than having a single repo with spaghetti code.如果您有 2 个模块(比如说登录和注册),最好将存储库分开以保持内容简洁明了,而不是使用带有意大利面条代码的单个存储库。

  2. This point is opinionated.这一点是自以为是的。 IMO you can have singleton repositories because they are stateless ie they do not hold any kind of data which may cause conflict between multiple ViewModels/Modules. IMO 你可以拥有 singleton 个存储库,因为它们是无状态的,即它们不包含任何可能导致多个 ViewModels/Modules 之间发生冲突的数据。

  3. Depends on you but it is much better to return Result.取决于你,但返回结果要好得多。 With Result you can handle Success Failure and Error Messages easily and return different Error Messages directly from repository rather than deciding in ViewModel what message to show.使用 Result,您可以轻松处理成功失败和错误消息,并直接从存储库返回不同的错误消息,而不是在 ViewModel 中决定要显示什么消息。 Messages can be either from server or internal exception messages.消息可以来自服务器或内部异常消息。

  4. SharedPreferences is a datasource. SharedPreferences 是一个数据源。 Yes you can manage preferences using repository pattern.是的,您可以使用存储库模式管理首选项。

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

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