简体   繁体   English

Android MVVM 应用架构:如何将 FirebaseFirestore 设置为存储库

[英]Android MVVM App Architecture: How to set up FirebaseFirestore as Repository

I want to create a app with the new architecture components and i already set up the views and the ViewModel.我想使用新的架构组件创建一个应用程序,并且我已经设置了视图和 ViewModel。 At the moment my app performs all Firestore queries in the ViewModel and it works to some extent.目前,我的应用程序在 ViewModel 中执行所有 Firestore 查询,并且在某种程度上起作用。 Google recommends that you should provide a Repository that caches some data and decides whether to fetch new data. Google 建议您应该提供一个 Repository 来缓存一些数据并决定是否获取新数据。 This makes perfectly sense for my application since a have several Fragments nested in my MainActivity and lots of other activites.这对我的应用程序非常有意义,因为在我的 MainActivity 和许多其他活动中嵌套了几个 Fragment。

I decided to implement the repository and created a Kotlin Object (Singleton) for my repository.我决定实现存储库并为我的存储库创建了一个 Kotlin 对象(单例)。 As a consequence i got the warning that i should not store a FirebaseFirestore instance in it because it contains a Context field (i need an instance to assign snapshotListeners).结果我收到警告,我不应该在其中存储 FirebaseFirestore 实例,因为它包含一个 Context 字段(我需要一个实例来分配快照监听器)。

Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

I completely understand this warning but i wonder how i should implement the Repository pattern with Firebase in my app without being in danger of causing a memory leak ?我完全理解这个警告,但我想知道我应该如何在我的应用程序中使用 Firebase 实现存储库模式而不会有导致内存泄漏的危险 Since Firebase and the new Architecure Components/Guidlines are both from Google i assume there are designed to work together but after doing some research i wasn't able to figure it out.由于 Firebase 和新的 Architecure 组件/指南都来自 Google,我认为它们旨在协同工作,但经过一些研究后,我无法弄清楚。

Does anyone know an effective way to implement a repository with Firebase snapshotListeners?有谁知道使用 Firebase snapshotListeners 实现存储库的有效方法吗?

It's been a while since I asked this question.我问这个问题已经有一段时间了。 Meanwhile, I have found a great way to solve this problem.同时,我找到了解决这个问题的好方法。 The best way is to make use of the repository pattern and Dependency Injection.最好的方法是利用存储库模式和依赖注入。 That means you have a class with a private field firebaseFirestore that implements an interface that defines all database operations ( RemoteRepository in my case).这意味着你有一个带有私有字段firebaseFirestore的类,它实现了一个定义所有数据库操作的接口(在我的例子中是RemoteRepository )。 The class itself is provided as a Singelton via Dependency Injection.类本身通过依赖注入作为 Singelton 提供。

class FirebaseRepository : RemoteRepository {
   private val firebaseFirestore = FirebaseFirestore.getInstance()

   override suspend fun saveSomething(...) {
     ...
   }

   override suspend fun getSomething(id: String) : T {
     return ...
   }


}

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

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