Making Android events reactive

We have made our API calls reactive, but what about our events? Remember the ToDoAdapter; we took a lambda, used it inside ToDoViewHolder, and created and passed the lambda at TodoListActivity. Quite messy. This should be reactive as well, shouldn't it? So, let's make the events reactive as well.

Subject plays an awesome role in making events reactive. As Subject is a great combination of Observable and Observer, we can use them as Observer inside Adapter and as Observable inside Activity, thus making passing events easy.

So, let's modify the ToDoAdapter as follows:

    class ToDoAdapter( 
      private val context:Context, //(1) 
      val onClickTodoSubject:Subject<Pair<View,ToDoModel?>>//(2) 
      ):RecyclerView.Adapter<ToDoAdapter.ToDoViewHolder>() { 
      private val inflater:LayoutInflater = 
LayoutInflater.from(context)//(3) private val todoList:ArrayList<ToDoModel> = arrayListOf()//(4) fun setDataset(list:List<ToDoModel>) {//(5) todoList.clear() todoList.addAll(list) notifyDataSetChanged() } override fun getItemCount(): Int = todoList.size override fun onBindViewHolder(holder: ToDoViewHolder?,
position: Int) { holder?.bindView(todoList[position]) } override fun onCreateViewHolder
(parent: ViewGroup?, viewType: Int): ToDoViewHolder { return ToDoViewHolder(inflater.inflate
(R.layout.item_todo,parent,false)) } inner class ToDoViewHolder(itemView:View):
RecyclerView.ViewHolder(itemView) { fun bindView(todoItem:ToDoModel?) { with(itemView) {//(6) txtID.text = todoItem?.id?.toString() txtDesc.text = todoItem?.todoDescription txtStatus.text = todoItem?.status txtDate.text = todoItem?.todoTargetDate onClick { onClickTodoSubject.onNext(Pair
(itemView,todoItem))//(7) } } } } }

The adapter looks cleaner now. We've got a Subject instance in the constructor, and when the itemView is clicked, we call the onNext event of the Subject and pass both the itemView and ToDoModel instance with help of Pair.

However, it still looks like something is missing. The onClick method is still a callback; can't we make it reactive as well? Let's do that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.85