简体   繁体   中英

observeForever inside a singleton object

I'm writing my first app in Kotlin and am using Firebase for auth,db & storage. I have singleton object to wrap each Firebase service to reduce coupling. In my Authentication object, I hold the current user in a LiveData to allow ViewModels to reference it and Fragments to observe it, and it works great. I would like to observe it also from the Database object, to allow it to keep the current user's Firestore document loaded. My Firebase objects are not Lifecycle aware so observeForever is my option. The function's comment states that: "You should manually call {@link #removeObserver(Observer)} to stop observing this LiveData.", but I didn't find any "finalize"/"onCleanUp"/... handlers in Kotlin objects. Should I worry about it (in my case I kind of want to really observe forever)?

code:

object Authentication {
    private val auth = FirebaseAuth.getInstance().apply {
        addAuthStateListener { _currentUser.value = currentUser }
    }

    private val _currentUser: MutableLiveData<FirebaseUser?> =
        MutableLiveData<FirebaseUser?>().apply { value = auth.currentUser }
    val currentUser: LiveData<FirebaseUser?> = _currentUser

...
}

object Database {
    init {
        Authentication.currentUser.observeForever { switchUserDocument(it) }
    }

...
}

Thanks::)

It looks like you do not need to remove observer from your Singletone you should ignore android lint in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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