Lifecycle-Delegates icon indicating copy to clipboard operation
Lifecycle-Delegates copied to clipboard

How to use in RecyclerView to make it's child (ViewHolder) lifecycle aware?

Open bipinvaylu opened this issue 3 years ago • 1 comments

Basically, I want to develop an Instagram kind of auto-play video in nested RecyclerView. So when the user scrolls and stops at a specific position and I would like to receive a callback like this is resumed/paused/stopped/destroyed. So I can make a proper call of ExoPlayer methods and make sure at a time only a single video is playing when the user is not scrolling.

It would be helpful if you can share a simple example of RecyclerView which ViweHolder receives the above-mentioend callbacks.

bipinvaylu avatar Nov 19 '21 10:11 bipinvaylu

Recycler view is a bit different, you must think about how to reuse views, when user do scroll, is not bound to lifecycle. Android lifecycle can help you to clear/init/pause/stop player according to android lifecycle, not scroll events. Here is an example:

class LifecycleOwnerDelegate(private val lifecycle: Lifecycle): LifecycleOwner {
    override fun getLifecycle(): Lifecycle = this.lifecycle
}

class Player {
    fun play() {}

    fun pause() {}
}

class MyRecyclerViewAdapter(private val lifecycle: Lifecycle): RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        ....
        return MyViewHolder(lifecycle, myInflateView)
    }

    inner class MyViewHolder(lifecycle: Lifecycle, itemView: View): RecyclerView.ViewHolder(itemView), LifecycleOwner by LifecycleOwnerDelegate(lifecycle) {
        private val myPlayer by lazyCreatableDestroyable(::Player, Player::play, Player::pause)

    }
}

Link184 avatar Nov 19 '21 11:11 Link184