Cătălin Florescu
Cătălin Florescu

Reputation: 5158

flatMap() in kotlin

If i make a Single invocation using Retrofit as example in Kotlin, i want to check the resulted answer and keep going with a Single or an error. As example

model.doRequest()
     .flatMap { t: Response ->
          if(!h.hasError) {
              return@flatMap model.doAnotherRequest()
          } else {
              return@flatmap Single.error<Throwable>(Throwable("error))
          }
      }

If i make another flatMap(), subscribe() or any other things, RxJava won't know that I want to continue with response given by the doAnowhtRequest(), instead will return Any!. How i can get data given by second request?

In Java, Single.error isn't interpreted so RxJava will continue to give me the response in next invocations.

Upvotes: 0

Views: 1833

Answers (1)

Fred
Fred

Reputation: 17085

Assuming you want to return the same thing as doAnotherRequest() the problem is with Single.error<Throwable>(Throwable("error)). You're hitting the compiler that you're returning a Single<Throwable>, but you want to return a Single<whatever doAnotherRequest returns>.

Say your doAnotherRequest returns Single<Foo>, then you'd want to return Single.error<Foo>(Throwable("error)), which will return a single that will emit an error with the given exception.

Kotlin tries to infer the type you want to return, but because you're returning 2 types that the "most common" type is Any, kotlin can only infer it's that you want to return.

Upvotes: 2

Related Questions