1

I'm using switchIfEmpty operator in RxJava to use a secondary observable when the primary observable doesn't have a value. Following is my code:

fun main(args: Array<String>) {
      getFirstObservable()
        .switchIfEmpty { getSecondObservable() }
        .subscribe { println(it) }
}

fun getFirstObservable() = Observable.empty<String>()
fun getSecondObservable() = Observable.just("String1", "String2")

However, even if the first observable is empty, it never emits values from the second observable, and nothing is printed in the output. Am I missing something?

akarnokd
  • 69,132
  • 14
  • 157
  • 192
Abhishek
  • 1,349
  • 8
  • 17

1 Answers1

3

Use normal parenthesis, not curly braces. It's a pretty common mistake with Kotlin when you need to provide an argument, not a lambda.

fun main(args: Array<String>) {
    getFirstObservable()
        // ----------- v --------------------- v --------------
        .switchIfEmpty ( getSecondObservable() )
        // ----------- ^ --------------------- ^ --------------
        .subscribe { println(it) }
}

fun getFirstObservable() = Observable.empty<String>()
fun getSecondObservable() = Observable.just("String1", "String2")
akarnokd
  • 69,132
  • 14
  • 157
  • 192