package keijumt.devandroid.viewmodel import android.arch.lifecycle.ViewModel import android.databinding.ObservableField import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import keijumt.devandroid.api.response.mapper.toAddressEntity import keijumt.devandroid.repository.PostalCodeRepository import javax.inject.Inject class ApiViewModel @Inject constructor(val postalCodeRepository: PostalCodeRepository) : ViewModel() { val postalCode = ObservableField<String>("") var address = ObservableField<String>() fun search() { if (postalCode.get().isNullOrEmpty()) { return } postalCodeRepository.search(postalCode.get()?.toInt()!!) .subscribeOn(Schedulers.io()) .subscribeBy( onSuccess = { postalCode -> if (postalCode.results != null) { val addressEntity = postalCode.toAddressEntity() address.set(addressEntity.address) } else { address.set("Address does not exist.") } }, onError = { address.set("") } ) } }