I was interested to find out what is the best way to respond to a item click of a recycler view.
Normally I would add a onclick() listener to the ViewHolder and pass ba
We generally need the Pojo/Model class from list on clicked index. I do it in following way:
1) Create a BaseRecyclerViewAdapter
abstract class BaseRecyclerViewAdapter : RecyclerView.Adapter() {
private val clickListenerPublishSubject = PublishSubject.create()
fun observeClickListener(): Observable {
return clickListenerPublishSubject
}
fun performClick(t: T?) {
t ?: return
clickListenerPublishSubject.onNext(t)
}
}
2) In any adapter (For example MyAdapter
)
class MyAdapter(private val events: List, context: Context) : BaseRecyclerViewAdapter() {
//... Other methods of RecyclerView
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is EventViewHolder) {
holder.eventBinding?.eventVm = EventViewModel(events[position])
holder.eventBinding?.root?.setOnClickListener({ _ ->
// This notifies the subscribers
performClick(events[position])
})
}
}
}
3) Inside the Activity
or Fragment
where click listener is needed
myAdapter?.observeClickListener()
?.subscribe({ eventClicked ->
// do something with clicked item
})