尝试将嵌套循环的旧 Java 函数转换为 RxJava 样式



我正在尝试将具有如此多嵌套过滤的旧Java代码转换为RxJava样式。

class DownloadTicket{
private interface TicketRepository{
Single<List<String>> getTickets();
}

public void filterAndDownloadTickets(TicketRepository ticketsRepository){
ticketsRepository.getTickets().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).doOnSuccess(journeyResultDtos -> {
for (JourneyResultDto journeyResultDto : journeyResultDtos) {
for (TicketBookingDto ticketBookingDto : journeyResultDto.getBookings().values()) {
if (ticketBookingDto.getBookingUuid().equals(bookingUUID)) {
for (TicketFileDto ticketFileDto : journeyResultDto.getTicketFiles().values()) {
if (ticketFileDto.getFileType().contains(CompanionActivity.FILETYPE_MOT)) {
// Here I'd like to receive the filer list, so I can perform some operation on it.
}
}
}
}
}
});
}

}

正如你所看到的,函数filterAndDownloadTickets包含太多嵌套的for循环,我尝试了使用flatMap,filter等将代码转换为RxJava的不同方法。但是,我仍然没有取得任何突破。

谁能帮我把它转换成RxJava?

我不完全确定您的数据模型,但这样的东西应该可以工作。 基本上,当您有一个对象列表并且想要发出列表中的每个对象时,您希望平面映射,然后当您想要转换并反对其子对象之一时,您想要映射,最后您想要过滤您的 if 条件。

ticketsRepository
.getTickets()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(journeyResultDtos -> journeyResultDtos) //map the list to into an Observable which emits every item in the list
.map(journeyResultDto -> journeyResultDto.getBookings()) //Map to the list of bookings
.flatMap(ticketBookingDtos -> ticketBookingDtos)//map the list to into an Observable which emits every item in the list
.filter(ticketBookingDto -> ticketBookingDto.getBookingUuid().equals(bookingUUID)) //apply first if condition
.map(ticketBookingDto -> journeyResultDto.getTicketFiles()) //Map to ticket files
.flatMap(ticketFileDtos -> ticketFileDtos)//map the list to into an Observable which emits every item in the list
.filter(ticketFileDto -> ticketFileDto.getFileType().contains(CompanionActivity.FILETYPE_MOT))//Apply second if
.subscribe(ticketFileDto -> {
//handle the object
});

相关内容

  • 没有找到相关文章

最新更新