1

I have this function which gets a parameter and first checks for its value. if it was null then gets its value from the result of fisrtFun() which returns a Single< String>.

after that either that parameter was null or not, it returns the result of secondFun() which gets that parameter as input

fun getUserEvents(id: String?): Single<String> {
    return if (userId == null) {
        firstFun().flatMap { id->
            secondFun(id)
        }
    } else {
        secondFun(id)
    }
}

But as you see I used if-else blocks and have written secondFun() multiple times

so I tried to make it cleaner

fun getUserEvents(id: String?): Single<String> {
    val id = userId ?: fisrtFun().blockingGet()!!
    return secondFun(id)
}

I want to know if there is a better way to achieve this functionality without using blockingGet() to avoid blocking the thread

1 Answers1

2

Something like this should work:

fun getUserEvents(id: String?): Single<String> {
    val idSingle = if (userId == null) firstFun() else Single.just(id)
    return idSingle.flatMap { id ->
        secondFun(id)
    }
}
ferini
  • 1,908
  • 14
  • 17