0

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.

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106

2 Answers2

1

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);
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

This should help.

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

   Single.create(single).map({
    if (it){
        return@map getCompleteable()
    }
    return@map Completable.complete()
})
karandeep singh
  • 2,294
  • 1
  • 15
  • 22