How to make this block of code written with RxKotlin cleaner and avoid blocking thread?

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

Upvotes: 1

Views: 144

Answers (1)

ferini
ferini

Reputation: 1958

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)
    }
}

Upvotes: 2

Related Questions