我正在使用此模式创建单例以帮助我进行Firebase操作,但不幸的是,它正在泄漏内存,这是我的代码。
class FirebaseDataSource(private val db: FirebaseFirestore,
private val firebaseAuth: FirebaseAuth,
private val firebaseFunctions: FirebaseFunctions,
private val firebaseStorage: FirebaseStorage,
private val firebaseInstanceId: FirebaseInstanceId) {
companion object {
@Volatile
private var INSTANCE: FirebaseDataSource? = null
fun getInstance(db: FirebaseFirestore = FirebaseFirestore.getInstance(),
firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance(),
firebaseFunctions: FirebaseFunctions = FirebaseFunctions.getInstance(),
firebaseStorage: FirebaseStorage = FirebaseStorage.getInstance(),
firebaseInstanceId: FirebaseInstanceId = FirebaseInstanceId.getInstance()
): FirebaseDataSource =
INSTANCE ?: synchronized(this) {
INSTANCE
?: FirebaseDataSource(db, firebaseAuth, firebaseFunctions, firebaseStorage, firebaseInstanceId).also { INSTANCE = it }
}
fun clearInstance() {
INSTANCE = null
}
}
}
并且我在这样的活动中使用它
private val firebaseDataSource = FirebaseDataSource.getInstance()
可以帮助我解决内存泄漏甚至为FirebaseDataSource设计更好的方法
答案 0 :(得分:1)
Kotlin具有顶层,线程安全的单例对象。为什么不尝试这样的事情:
object FirebaseDataSource {
private val db: FirebaseFirestore = FirebaseFirestore.getInstance()
private val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance()
private val firebaseFunctions: FirebaseFunctions = FirebaseFunctions.getInstance()
private val firebaseStorage: FirebaseStorage = FirebaseStorage.getInstance()
private val firebaseInstanceId: FirebaseInstanceId = FirebaseInstanceId.getInstance()
fun doStuff() {
db.doStuff()
}
}
然后使用它
FirebaseDataSource.doStuff()