Android Kotlin et RxJava exemple


Premier exemple réimplémenté dans Kotlin et utilisant RxJava pour une interaction plus propre.

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import rx.subjects.PublishSubject

public class SampleAdapter(private val items: Array<String>) : RecyclerView.Adapter<SampleAdapter.ViewHolder>() {

    // change to different subjects from rx.subjects to get different behavior
    // BehaviorSubject for example allows to receive last event on subscribe
    // PublishSubject sends events only after subscribing on the other hand which is desirable for clicks
    public val itemClickStream: PublishSubject<View> = PublishSubject.create()
    override fun getItemCount(): Int {
        return items.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder? {
        val v = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_row_item, parent, false);
        return ViewHolder(view)

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    public inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val textView: TextView by lazy { view.findViewById( as TextView }

        init {
            view.setOnClickListener { v -> itemClickStream.onNext(v) }

        fun bind(text: String) {
            textView.text = text

L'utilisation est assez simple alors. Il est possible de s'inscrire sur des threads distincts en utilisant les fonctionnalités de RxJava.

val adapter = SampleAdapter(arrayOf("Hello", "World"))
adapter.itemClickStream.subscribe { v ->
    if ( == {
        // do something