Search code examples
androidandroid-lifecycle

How can I get LifecycleOwner reference in RecyclerView.Adapter?


At present, I use mLifecycleOwner = mContext as LifecycleOwner to get LifecycleOwner, it can work, but I don't think it's a good code.

How can I get LifecycleOwner from ListAdapter?

class VoiceAdapters (private val aHomeViewModel: HomeViewModel, private val mPlay: PlayInterface):
        ListAdapter<MVoice, VoiceAdapters.VoiceViewHolder>(MVoiceDiffCallback()) {

    private lateinit var mContext: Context
    private lateinit var mLifecycleOwner:LifecycleOwner

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoiceViewHolder {
        mContext = parent.context
        mLifecycleOwner = mContext as LifecycleOwner

        return VoiceViewHolder(
            LayoutVoiceItemBinding.inflate(LayoutInflater.from(parent.context), parent, false).also {               
               it.lifecycleOwner = mLifecycleOwner
               it.aHomeViewModel = aHomeViewModel
            }
        )
    }

    ...
}

Solution

    1. Pass it as constructor param in the VoiceAdapters
    2. Create extension property:
       val View.lifecycleOwner get() = ViewTreeLifecycleOwner.get(this)`
    

    then access it: parent.lifecycleOwner

    1. Resolve it only once:
    
     override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoiceViewHolder {
           if(!::lifecycleOwner.isInitialized){
            lifecycleOwner = parent.context as LifecycleOwner
          }
    }
    

    They are pointing to the same LifecycleOwner, the Context that was used to inflate the layout.

    ViewTreeLifecycleOwner.get(view) is convenient way to obtain the view's underlying LifecycleOwner. Therefore, my two cents go to option 1 or 2.