where findViewTreeLifecycleOwner() should be called in a custom view?

Viewed 2322

Fragment 1.3.0 introduced the method view.findViewTreeLifecycleOwner() to get the lifecycleOwner of a view. In a fragment, this method returns null before onViewCreated().

I have some initialization to do in a custom view using coroutines so I need to call findViewTreeLifecycleOwner().lifecycleScope to get the coroutine scope. What is best the place to call it in the view?

At first I tried to call it in the constructor since well, it's made for initialization but it's call before the fragment's onViewCreated() so the method returns null. So I tried to put it in onAttachedToWindow() and there it works but I really don't know if it's a good idea to make initialization stuff here.

class TestView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) {

    init {
        // return null here as constructor is called before fragment's onViewCreated()
        findViewTreeLifecycleOwner()!!.lifecycleScope.launchWhenStarted { 
            ...
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        // here it works because it's called after  fragment's onViewCreated()
        findViewTreeLifecycleOwner()!!.lifecycleScope.launchWhenStarted {
            ...
        }
    }
}
0 Answers
Related