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

Fragment生命周期监听方法不正确 #15

Closed
start141 opened this issue Jan 18, 2021 · 4 comments
Closed

Fragment生命周期监听方法不正确 #15

start141 opened this issue Jan 18, 2021 · 4 comments
Labels
bug Something isn't working

Comments

@start141
Copy link

当前的监听方法通过fragment.lifecycle添加了Observer,
fragment.lifecycle关联的是fragment的生命周期,而非fragment.view的生命周期,

fragment.lifecycle.addObserver { destroyed() }

由于fragment.view活跃的生命周期存在明显比fragment活跃生命周期短的情况,
(如采用Navigation库管理fragment(attach/detach))
正确的做法是采用fragment.viewLifecycleOwner.lifecycle添加Observer。

Simple one-liner ViewBinding in Fragments and Activities with Kotlin
中fragment生命周期监听的方法是正确的
(其中onDestroy回调与fragment.onDestroyView()回调对应)

fragment.lifecycle.addObserver(object : DefaultLifecycleObserver {
    override fun onCreate(owner: LifecycleOwner) {
        fragment.viewLifecycleOwnerLiveData.observe(fragment) { viewLifecycleOwner ->
            viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onDestroy(owner: LifecycleOwner) {
                    binding = null
                }
            })
        }
    }
})

PS: observers可以不额外手动remove,因为fragment.lifecycle和LiveData都在DESTROYED时做了反注册。

@hi-dhl
Copy link
Owner

hi-dhl commented Jan 18, 2021

非常感谢, 你是对的, view 生命周期比 fragment 周期短,也确实存在多种情况, view 被销毁了,而fragment 依然存在,也可能会出现造成多个 Observer 的情况,而 ViewBinding 和 DataBinding 都是 View 相关的,应该使用 viewLifecycleOwner, 我会在下一个版本一起修复这个问题,再次感谢

@hi-dhl hi-dhl added the bug Something isn't working label Jan 18, 2021
@hi-dhl
Copy link
Owner

hi-dhl commented Jan 18, 2021

我指的不是 binding 中添加 addObserver, 而是 fragment.lifecycle 和 fragment.viewLifecycleOwner 可能是会存在多个的,

@hi-dhl
Copy link
Owner

hi-dhl commented Jan 25, 2021

非常感谢你的提交和建议,这个问题在 1.0.9 上修复了

@hi-dhl hi-dhl closed this as completed Jan 25, 2021
@aprz512
Copy link

aprz512 commented May 16, 2021

registerFragmentLifecycleCallbacks 会不会更直观一点,不过注册时机需要在获取 value 的时候。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants