Ad

Convert Single To Boolean (Kotlin)

- 1 answer

I have a mutable live data which I use to adjust visibility(with binding adapter) in my layout. I use the boolean value of live data to achieve this with the code below.

@BindingAdapter("viewVisibility")
fun setVisibility(view: View, visible: Boolean) {
    view.visibility = if (visible) View.VISIBLE else View.GONE
}

To get this data I use the following method

   Flowable.just(
Sdk().searchContact(CHATBOT_NAME)).map {!(it.isEmpty()) }

it.isEmpty() gives me a Flowable < Single< Boolean>> instead of Flowable and I want to convert this Single to a boolean(to give it as a parameter to my binding adapter) but I could not find a way to convert it. My temporary (probably bad) solution is below.

  it.blockingLast().isEmpty() // Blocking last gives me a list so I can get non-single boolean with isEmpty. Since I need one element from search contact method blocking last or first works same in this case.

Is this an acceptable solution? How can I convert Single to normal Boolean?

Ad

Answer

it's me again,try following code:

fun doesExist(): Flowable<Boolean> {
   return Flowable.just(Single.just(Sdk().searchContact(CHATBOT_NAME)).map{ it.isEmpty()}).map {it.blockingGet() }
}
Ad
source: stackoverflow.com
Ad