ViewModel类可以实现LifecycleObserver吗?

时间:2018-12-16 17:06:21

标签: android android-jetpack

在阅读ViewModel overview时,我想知道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
    }
}

1 个答案:

答案 0 :(得分:2)

如果您不担心列表列表的作用是恢复/暂停。您可以使用自定义实时数据来实现。 您可以使用自定义实时数据(例如UserProfileLiveData)来扩展实时数据。

请参阅扩展实时数据- https://developer.android.com/topic/libraries/architecture/livedata#extend_livedata