Search code examples
androidkotlinrx-kotlin2

Android rxKotlin crash in subcribe combineLatest


I want enable/disable button when code & name is not empty.

My code:

btnAddItem.isEnabled = false

    val codeIsValid = RxTextView.textChanges(txvCode)
        .debounce(350, TimeUnit.MILLISECONDS)
        .map { code ->
            code.isNotEmpty()
        }

    val nameIsValid = RxTextView.textChanges(edtName)
        .debounce(350, TimeUnit.MILLISECONDS)
        .map { name ->
            name.isNotEmpty()
        }

    disposableEnableButtonSave = Observables.combineLatest(codeIsValid, nameIsValid) 
        { b1, b2 -> b1 && b2 }
        .subscribe {
            if (btnAddItem.isEnabled != it){
                btnAddItem.isEnabled = it //crash here.
            }
        }

But it error when run:

Logcat:

io.reactivex.exceptions.OnErrorNotImplementedException: Animators may only be run on Looper threads
android.util.AndroidRuntimeException: Animators may only be run on Looper threads

code crash is enable/disable button.

btnAddItem.isEnabled = it

Solution

  • Try this

    runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (btnAddItem.isEnabled != it){
                   btnAddItem.isEnabled = it
                }
            }
    });