Home > Blockchain >  How to use Android LifecycleOwner in dialog
How to use Android LifecycleOwner in dialog

Time:12-28

I want to use mvvm in Dialog but I don't know how to pass LifecycleOwner to observe

class CommonDialog(context: Context) : Dialog(context, R.style.AppMaskStatusTheme) {

    private val viewBinding: DialogSportOrderBinding by lazy { DialogSportOrderBinding.inflate(LayoutInflater.from(context)) }
    private val viewModel by lazy { ViewModelProvider(context as ViewModelStoreOwner)[SportOrderViewModel::class.java] }

 init {
        setContentView(viewBinding.root)

        viewModel.sportOrderList.observe(***what to pass here?***, androidx.lifecycle.Observer {

        })
    }
}

I have tried context as LifecycleOwner, context as AppCompatActivity but all fail

please help me, thanks!

CodePudding user response:

You can create your own LifecycleOwner like this

class MyLifecycleOwner() : LifecycleOwner {
    private val mLifecycleRegistry: LifecycleRegistry by lazy { LifecycleRegistry(this) }

    init {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    fun stop() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    }

    fun start() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    override fun getLifecycle(): Lifecycle = mLifecycleRegistry
}

Then your Dialog class will be like this

class CommonDialog(context: Context) : Dialog(context, R.style.AppMaskStatusTheme) {

    private val viewBinding: DialogSportOrderBinding by lazy { DialogSportOrderBinding.inflate(LayoutInflater.from(context)) }
    private val viewModel by lazy { ViewModelProvider(context as ViewModelStoreOwner)[SportOrderViewModel::class.java] }

    private val lifeCycleOwner: MyLifecycleOwner by lazy { MyLifecycleOwner() }

    init {
        setContentView(viewBinding.root)

        viewModel.sportOrderList.observe(lifeCycleOwner, {

        })
    }

    override fun onStart() {
        super.onStart()
        lifeCycleOwner.start()
    }

    override fun onStop() {
        super.onStop()
        lifeCycleOwner.stop()
    }
}

Read more about Lifecycle-Aware Components at here

CodePudding user response:

android.content.Context does not implement android.arch.lifecycle.LifecycleOwner.

You'd have to pass an instance of AppCompatActivity, which implements android.arch.lifecycle.LifecycleOwner (or any other class which does that).

or cast (AppCompatActivity) context, when context is an instanceof AppCompatActivity.

  • Related