Lifecycle-Delegates
Lifecycle-Delegates copied to clipboard
How to use in RecyclerView to make it's child (ViewHolder) lifecycle aware?
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.
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)
}
}