RxJava2如果没有元素,可能返回空的Observable

时间:2017-06-19 09:44:49

标签: kotlin rx-java2 rx-kotlin

使用JavaRx 2中的Maybe类型比flatMaptry/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}似乎有点软糊涂层}。只是想知道是否有更简洁的方法来做到这一点?

0 个答案:

没有答案