Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PublishLiveDataKtx not remove observer by lifecycle event #26

Open
jukov opened this issue Dec 17, 2019 · 0 comments
Open

PublishLiveDataKtx not remove observer by lifecycle event #26

jukov opened this issue Dec 17, 2019 · 0 comments

Comments

@jukov
Copy link

jukov commented Dec 17, 2019

Code from https://github.com/Shopify/livedata-ktx/blob/master/livedata-ktx/src/main/java/com/shopify/livedataktx/PublishLiveDataKtx.kt:

   override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        val observeSinceVersion = version
        val wrapper = observerWrappers.getOrElse(observer, Observer {
            if (!isPublish || version > observeSinceVersion) {
                observer.onChanged(it)
            }
        })
        observerWrappers.putIfAbsent(observer, wrapper)
        super.observe(owner, wrapper)
    }

    override fun observeForever(observer: Observer<in T>) {
        val observeSinceVersion = version
        val wrapper = observerWrappers.getOrElse(observer, Observer {
            if (!isPublish || version > observeSinceVersion) {
                observer.onChanged(it)
            }
        })
        observerWrappers.putIfAbsent(observer, wrapper)
        super.observeForever(wrapper)
    }

    override fun removeObserver(observer: Observer<in T>) {
        observerWrappers.get(observer)?.let { super.removeObserver(it) }
        observerWrappers.removeIfPresent(observer)
    }

When we call observeForever(), all looks good and calling removeObserver() with same Observer working as expected.

But if we call observe() and later lifecycle move to Destroyed state, system call removeObserver() with wrapped Observer, and we try to find it in observedWrappers among non-wrapped observers. Pair instances with weak references to observers just accumulated in array until livedata instance not GCed.

I don't know clear solution of this problem, suppose we can check wrapped and non-wrapped observers both when removing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant