Alex Suslov
Alex Suslov

Reputation: 75

How combine the flatmap and previous Single

There is next working code, which combine results of .connect() and .auth().

auth() depends on the result of connect(). In total it necessary to combine api and auth results into Connection object.

fun getConnection(token: String): Single<Connection> {
  return connect()
            .map { Api(it) }
            .flatMap { api -> api.auth(token)
                                 .map { Connection(api, it) }
                     }     
}

IMHO this code is smelling. May be it has more optimal solution for getting Connection without an internal mapping in rxjava2?

Upvotes: 0

Views: 2300

Answers (1)

tynn
tynn

Reputation: 39843

In your case you don't actually need to use map() at all. Just create your Api object within flatmap().

fun getConnection(token: String): Single<Connection> {
  return connect().flatMap { conn ->
    val api = Api(conn)
    api.auth(token).map { Connection(api, it) }
  }     
}

Upvotes: 2

Related Questions