0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RxKotlinをつかってみたメモ書き

Last updated at Posted at 2019-09-18

以前の現場でRxJavaを使って開発してたのですが、
RxKotlinもあるよ、ということなので、暇つぶしにつかってみた。

app/build.gradle
android {
    ・・・()・・・
}
dependencies {
    ・・・()・・・
    implementation 'io.reactivex.rxjava2:rxjava:2.2.4'
    implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
}

ライブラリは上記3つのみ追加すればOK。

RxKotlinBasicDialogFragment.kt
package com.example.myapplication

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.rxkotlin.toObservable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.dialog_reactive.*

class RxKotlinBasicDialogFragment : DialogFragment() {

    private lateinit var mDisposable: Disposable
    private var mResult: String = ""

    companion object {
        fun newInstance(): RxKotlinBasicDialogFragment {
            return RxKotlinBasicDialogFragment()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val anyObservable = getList().toObservable()
        mDisposable = anyObservable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeBy(
                onNext = {
                    Log.i("onNext", it.toString())
                    mResult += "$it, "
                },
                onError = {
                    Log.i("onError", it.toString())
                },
                onComplete = {
                    Log.i("onNext", "DONE!!")
                    resultTextView.text = mResult
                }
            )
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_reactive, container, false)
    }

    override fun onDestroy() {
        super.onDestroy()
        mDisposable.dispose()
    }


    private fun getList(): List<Any> {
        return listOf(true, 1, 2, "Three", 4.0f, 4.5, "Five", false)
    }
}

device-2019-09-18-173150.png

あとで、FlatMapとかzipもためしてみる。。。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?