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 back results to the activity/fragment through a interface.
I thought about adding a Observable in the onBindViewHolder but i do not want to create a new Observable for every item binding.
We generally need the Pojo/Model class from list on clicked index. I do it in following way:
1) Create a
BaseRecyclerViewAdapter
2) In any adapter (For example
MyAdapter
)3) Inside the
Activity
orFragment
where click listener is neededI would suggest you to do with your initial aproach of an observable per element on click, but in order to avoid create a new observable every time you can just cache the items emitted the first time using cache.
You can use RxBinding and then create a subject inside of your adapter, then redirect all the events to that subject and just create a getter of the subject to act as an observable and finally just subscribe you on that observable.
An usage example could be:
My solution was much like @epool 's except use EventBus model.
First, create a RxBus: RxBus.java
Then, you have two way to use RxBus. Create your custom Application class with RxBus reference or create RxBus in Activity/Fragment then pass it to adapter. I'm use the first.
MyApp.java
then use
to get RxBus instance.
The usage of RxBus in Adpater was like this:
You can send any class with _bus.send(), which We will recieve in the Activity:
About unsubscribe.
In MyRecyclerAdapter call _sub.unsubscribe() in clearup() methods and call _sub.unsubscribe() in Activity's onDestory().
Step 1: Move the business logic out of the activities to domain classes/services
Optional: Use https://github.com/roboguice/roboguice to easily wire up your services with each other.
Step 2:
@Inject
(or just set) your service into your adapterStep 3: Grab
https://github.com/JakeWharton/RxBinding
and use the super powers in your adapter:Step 4: Get a runtime crash and learn how to deal with subscriptions
Step 5: PROFIT :)