How to handle Item clicks for a recycler view using RxJava

后端 未结 5 700
有刺的猬
有刺的猬 2021-02-01 21:49

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

5条回答
  •  遇见更好的自我
    2021-02-01 22:50

    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
    
                    })
    

提交回复
热议问题