在不使用 Room 的情况下使用 LiveData 和 ViewModel
Using LiveData and ViewModel without using Room
对于 android MVVM 架构,在我见过的所有示例中,人们要么使用 Room 来 store/retrieve 数据,要么直接从 API 通过存储库调用获取数据 class.
我既没有进行 API 调用,也没有使用我的 Room 数据库来存储数据。但是我需要我的 ViewModel 从存储库中获取数据并将其传递给我的 Actvity。
如果您不打算使用 Room 在本地保存数据,您的存储库 class 是否可以继承应用程序 class 以便保存静态 variables/companion 对象?
有什么好的处理方法?
一般来说,在软件工程中,存储库用于从应用程序的其余部分(通常直接是业务层)中抽象出数据层(数据库、Web 服务),预订网站的这种模式就是一个很好的例子:
它通过 Publish/Subscribe 异步连接接收更新并将它们发送到其他组件。所以组件之间是相互独立的。
所以 Repository 只是一个简单的中介 class,用于使应用程序更加模块化,以便您可以更轻松地交换部分,并确保应用程序的其余部分不会打扰 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 MVVM 架构,在我见过的所有示例中,人们要么使用 Room 来 store/retrieve 数据,要么直接从 API 通过存储库调用获取数据 class.
我既没有进行 API 调用,也没有使用我的 Room 数据库来存储数据。但是我需要我的 ViewModel 从存储库中获取数据并将其传递给我的 Actvity。
如果您不打算使用 Room 在本地保存数据,您的存储库 class 是否可以继承应用程序 class 以便保存静态 variables/companion 对象?
有什么好的处理方法?
一般来说,在软件工程中,存储库用于从应用程序的其余部分(通常直接是业务层)中抽象出数据层(数据库、Web 服务),预订网站的这种模式就是一个很好的例子:
它通过 Publish/Subscribe 异步连接接收更新并将它们发送到其他组件。所以组件之间是相互独立的。
所以 Repository 只是一个简单的中介 class,用于使应用程序更加模块化,以便您可以更轻松地交换部分,并确保应用程序的其余部分不会打扰 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 或其他任何东西。