package com.hanwha.morakmorak.extensions

import androidx.databinding.ObservableField
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import timber.log.Timber

/**
 * Created by aaron on 08/07/2019
 */

fun <T> Single<T>.with(): Single<T> = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

fun <T> ObservableField<T>.asObservable() : Observable<T> {
    return Observable.create { emitter ->

        emitter.onNext(get()!!)

        val callback = object : androidx.databinding.Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(observable: androidx.databinding.Observable, i: Int) {
                if (observable === this) {
                    Timber.d(get().toString())
                    emitter.onNext(get()!!)
                }
            }
        }

        addOnPropertyChangedCallback(callback)
        emitter.setCancellable { removeOnPropertyChangedCallback(callback) }
    }
}

object RxUtils