阅读ViewModel概述,我想知道一个ViewModel
同时成为LifecycleObserver
是否可以接受?我的意图是在用户不与UI交互时断开Firebase监听器,并在用户与UI交互时重新连接它。就我所做的和所知道的而言,它完美地运作。但是,我担心这样做可能有问题(例如内存泄漏)。如果是这样,请问有替代方法吗?
class UserProfileViewModel : ViewModel(), LifecycleObserver {
companion object {
private const val TAG = "ProfileViewModel"
}
private lateinit var mUserProfile: MutableLiveData<DocumentSnapshot>
private var mRegistration: ListenerRegistration? = null
override fun onCleared() {
Log.d(TAG, "onCleared")
disconnectListener()
}
fun getUserProfile(): LiveData<DocumentSnapshot> {
if (!::mUserProfile.isInitialized) {
mUserProfile = MutableLiveData()
}
return mUserProfile
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun connectListener() {
Log.d(TAG, "connectListener")
val user = FirebaseAuth.getInstance().currentUser
if (user == null) {
Log.w(TAG, "User not signed in.")
return
}
val firestore = FirebaseFirestore.getInstance()
val docRef = firestore.collection(UsersContract.COLLECTION_NAME).document(user.uid)
mRegistration = docRef.addSnapshotListener { snapshot, exception ->
if (exception != null) {
Log.w(TAG, "Failed to fetch user data", exception)
return@addSnapshotListener
}
if (snapshot != null && snapshot.exists()) {
mUserProfile.value = snapshot
}
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun disconnectListener() {
Log.d(TAG, "disconnectListener")
mRegistration?.remove()
mRegistration = null
}
}
LiveData
是否会作为ViewModel
的属性呢? - wonsuc