RecyclerView item click using RxJava2
First of all thanks for liking my previous article Auto ViewPager slider using RxJava2. If you haven’t read that article then I would highly recommend to read that article.
In this article I’ll tell you guys how you can set a click listener on RecyclerView items using RxJava2. I’ve seen many of the developers are using RxJava in their Android project but still they are using interfaces(which I won’t cover in this article) to interact between their RecyclerView adapter and View(Activity/Fragment).
So I thought of writing this article to explain how you guys can use RxJava to listen to the click events of your RecyclerView. I’ve written all the code using Kotlin and I’ve just started using Kotlin so please comment below if you find any issues in the code or the code can be optimised more.
So guys to interact between our view and recyclerview adapter I’ve used RxJava Subjects. Now what is a Subject, as per RxJava wiki :
Subjectis a sort of bridge or proxy that acts both as an
Subscriberand as an
Observable. Because it is a Subscriber, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items.
So as you have seen a Subject acts both as Subscriber and an Observable. So what we will be doing is in our adapter our Subject will act as an Observable and in our view we will subscribe to this subject so it will work as a Subscriber in our view.
Now there are multiple types of Subjects available in RxJava which you can checkout here. For our use case we will be using PublishSubject. So what is a PublishSubject, lets get back to the RxJava wiki for its definition.
Subject that, once an
Observerhas subscribed, emits all subsequently observed items to the subscriber.
So now we know what we will be using so lets get to the fun part(show me some code). So lets start with our RecyclerView Adapter:
private val clickSubject = PublishSubject.create<String>()
In our adapter I create a global variable of PublishSubject<String> which will emit String items. So in our ViewHolder class where we setup our click listener on an item we will call this clickSubject and call .onNext(item) on it. So whenever a click event comes our subject will emit the event.
Then we will create a method/function which will return an Observable<String> like this :
So here our adapter work id done. Now we will move to our view and call this getClickListener() function on our adapter reference and subscribe to this Observable<String> like this:
So guys that’s it for this tutorial and you can find the sample projecton github : RxRecyclerItemClick.
Hope you liked this tutorial. Constructive feedback is most welcomed.