Kristy Welsh
Kristy Welsh

Reputation: 8340

Better way to chain rxjava2 calls with conditional operations

I have the following code, that does one single call, gets the result of the call, which is a boolean, then makes the second call if the result is false.

private fun linkEmailAndTextTogether(contactPhoneNumber: ContactPhoneNumbers,phoneNumber : PhoneNumber) {
    val single = SingleOnSubscribe<Boolean> {
        contactPhoneNumber.doesEmailContactExist(phoneNumber)
    }
    Single.create(single)
            .subscribeOn(Schedulers.io())
            .subscribeWith(object : SingleObserver<Boolean> {
                override fun onSuccess(phoneNumberDoesExist: Boolean) {
                    if (!phoneNumberDoesExist) {
                        val completable = CompletableOnSubscribe {
                            contactPhoneNumber.linkEmailAndTextTogether(phoneNumber)
                        }
                        compositeDisposable.add(Completable.create(completable)
                                .subscribeOn(Schedulers.io())
                                .subscribe())
                    }
                }

                override fun onSubscribe(d: Disposable) {
                    compositeDisposable.add(d)
                }

                override fun onError(e: Throwable) {
                    Timber.e(e,e.localizedMessage)
                }


            })
}

It seems like there should be a more elegant way to do this in some kind of chain.

Upvotes: 0

Views: 740

Answers (2)

karandeep singh
karandeep singh

Reputation: 2334

This should help.

val single = SingleOnSubscribe<Boolean> {
     getSingle()
   }

   Single.create(single).map({
    if (it){
        return@map getCompleteable()
    }
    return@map Completable.complete()
})

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157457

you could use the flatMap operator - the downside is that you won't know if the first or the second failed.

  Single.just(phoneNumber)
       .subscribeOn(Schedulers.io())
       .map { it -> contactPhoneNumber.doesEmailContactExist(it) }
       .flatMap { it ->
             if (it) {
                 return@flatMap contactPhoneNumber.linkEmailAndTextTogether(phoneNumber)
              }
              Single.just(it)
        }.subscribe({}, Throwable::printStackTrace);

Upvotes: 1

Related Questions