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 kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.launch import javax.inject.Inject class AsyncViewModel @Inject constructor() : BaseViewModel() { fun async() { val calc = Task(object : Task.Callback<Int> { override fun execute(value: Int) { println("callback is ${value}") } }) calc.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } fun coroutine() { launch(UI) { val result = calc(3).await() * calc(5).await() println(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 = { println(it) } ) addDisposable(disposable) } fun rxCalc(num: Int) = Single.create<Int> { println(Thread.currentThread().name) it.onSuccess(num * num) }.subscribeOn(Schedulers.computation()) }