Newer
Older
DevAndroid / app / src / main / java / keijumt / devandroid / viewmodel / AsyncViewModel.kt
package keijumt.devandroid.viewmodel

import android.os.AsyncTask
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import keijumt.devandroid.common.Task
import keijumt.devandroid.databinding.SingleLiveEvent
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import javax.inject.Inject

class AsyncViewModel @Inject constructor() : BaseViewModel() {

    val toastMessage = SingleLiveEvent<String>()

    fun async() {
        val calc = Task(object : Task.Callback<Int> {
            override fun execute(value: Int) {
                toastMessage.value = "asynctask value is ${value}"
            }
        })
        calc.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
    }

    fun coroutine() {
        launch(UI) {
            val result = calc(3).await() * calc(5).await()
            toastMessage.value = "coroutine processing value is ${result}"
        }
    }

    fun calc(num: Int) = async {
        return@async num * num
    }

    fun rx() {
        val disposable = Singles
                .zip(rxCalc(3), rxCalc(5)) { num1, num2 -> num1 * num2 }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeBy(
                        onSuccess = {
                            toastMessage.value = "rxjava processing value is ${it}"
                        }
                )
        addDisposable(disposable)
    }

    fun rxCalc(num: Int) = Single.create<Int> {
        it.onSuccess(num * num)
    }.subscribeOn(Schedulers.computation())
}