使用JavaRx 2中的Maybe
类型比flatMap
和try/catch
有更好/更惯用的方法吗?以下示例采用Maybe<User>
并尝试为其预订航班的随机票证。如果用户不存在,请返回空Observable
。
fun bookRandomTicketFor(userId: UUID): Observable<Ticket> {
val agencies = travelAgents() // Observable<TravelAgency>
val user = findById(userId) // Maybe<User>
val location = locate() // Observable<GeoLocation>
return Observable
.just(user.toObservable())
.flatMap { usr ->
try {
usr.zipWith(location, { aUser, location ->
agencies
.flatMap { agency ->
agency
.search(aUser, location) // Observable<Flight>.
.toList() // Convert to List<Flight>.
.toObservable() // And to Observable<List<Flight>>.
.flatMap { flights -> // So it can be shuffled,
Observable.just( // giving a random order.
shuffle(flights as MutableList<Flight>)[0]
)
}
}.firstElement() // Now take the first randomly shuffled Flight.
}).flatMap { flight ->
book(user.toObservable(), flight.toObservable())
}
} catch (ex: Exception) {
Observable.empty<Ticket>()
}
}
.doOnSubscribe { Logger.log("Random ticket: start for $userId") }
.doOnComplete { Logger.log("Random ticket: exit for $userId") }
}
将Maybe<User>
转换为Observable
并从Observable<Observable<User>>
开始,我可以flatMap
和{{1}似乎有点软糊涂层}。只是想知道是否有更简洁的方法来做到这一点?