android - 在不使用 Room 的情况下使用 LiveData 和 ViewModel

标签 android android-architecture-components android-livedata android-viewmodel android-mvvm

对于 android MVVM 架构,在我看到的所有示例中,人们要么使用 Room 来存储/检索数据,要么通过 Repository 类直接从 API 调用中获取数据。

我既没有进行 API 调用,也没有使用我的 Room 数据库来存储数据。但我需要我的 ViewModel 从存储库中获取数据并将其传递到我的 Actvity。

如果您不打算使用 Room 在本地保存数据,您的 Repository 类是否可以继承 Application 类,以便您可以保存静态变量/伴随对象?

处理这种情况的好方法是什么?

最佳答案

一般来说,在软件工程中,存储库用于从应用程序的其余部分(通常直接是业务层)中抽象出数据层(数据库、Web 服务),一个很好的例子就是预订网站的架构:

Repository style

它通过发布/订阅 异步连接接收更新并将它们发送到其他组件。所以组件之间是相互独立的。
所以 Repository 只是一个简单的中介类,用于使应用程序更加模块化,以便您可以更轻松地交换部分,并确保应用程序的其余部分不会打扰 DB 连接或 HTTP 调用等。所以从技术上讲,您可以从 Application(或其他任何东西)继承并使用它来保存静态变量等。

但是如解释here :

The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.

所以这完全取决于您,您可以根据需要使用存储库样式,它完全不受 Room 或其他任何东西的影响。

关于android - 在不使用 Room 的情况下使用 LiveData 和 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550969/

相关文章:

java - 盖乐世 Note 4 模拟器

android - 无法在 Android 设备上获取任何位置,而 Google map 可以

android - Android MVVM按功能打包和按层打包哪个更好?

android - Room 数据库的 Drop 删除触发器

android - 在 WorkManager 中使用 RxWorker 进行 api 调用

android - Notification PendingIntent Intent extras 被另一个通知覆盖

android - 如何在 Android Studio 0.5.4 中使用 PhoneGap?

多次调用 Android LiveData observe

android - emit 和 emitSource 与 LiveData 之间有什么区别? (如实时用例)

android - 应用程序关闭后,ViewModel 和 LiveData 不会被删除。为什么?