首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用RxJava将多个对象转换为一个对象?

如何使用RxJava将多个对象转换为一个对象?
EN

Stack Overflow用户
提问于 2018-10-25 05:06:56
回答 2查看 111关注 0票数 0

我有一个日历对象,里面有多个不同对象的列表,比如:,EstimateWorkOrderBlockTime

因此,为了显示所有这些Calendar事件,我计划创建类型为event的CalendarItem对象并添加该事件。

代码语言:javascript
复制
public class CalendarItem {

private int type;
private Task task;
private Estimate estimate;
private WorkOrder workOrder;
private BlockTime blockTime;

public CalendarItem() {
}
}

我有这个RxJava函数:

代码语言:javascript
复制
Disposable disposable = calendarRepository.getCalendar(startDate, endDate)
    .subscribeOn(Schedulers.io())
    .flatMap((Function<Calendar, Publisher<List<CalendarItem>>>) calendar -> {
      List<Task> tasks = calendar.getTasks();
      List<WorkOrder> workOrders = calendar.getWorkOrders();
      List<BlockTime> blockTimes = calendar.getBlockTimes();
      List<Estimate> estimates = calendar.getEstimates();

      List<CalendarItem> calendarItems = new ArrayList<>();

      if(tasks != null) {
        for(Task t : tasks) {
          CalendarItem item = new CalendarItem();
          item.setType(Constants.CALENDAR_TASK);
          item.setTask(t);
          calendarItems.add(item);
        }
      }

      if(workOrders != null) {
        for(WorkOrder w : workOrders) {
          CalendarItem item = new CalendarItem();
          item.setType(Constants.CALENDAR_WORK_ORDER);
          item.setWorkOrder(w);
          calendarItems.add(item);
        }
      }

      if(estimates != null) {
        for(Estimate e : estimates) {
          CalendarItem item = new CalendarItem();
          item.setType(Constants.CALENDAR_ESTIMATE);
          item.setEstimate(e);
          calendarItems.add(item);
        }
      }

      if(blockTimes != null) {
        for(BlockTime b : blockTimes) {
          CalendarItem item = new CalendarItem();
          item.setType(Constants.CALENDAR_BLOCKED_TIME);
          item.setBlockTime(b);
          calendarItems.add(item);
        }
      }

      return Flowable.just(calendarItems);
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(calendarItems -> view.displayCalendar(calendarItems), view::handleError);

如何改进flatMap()运算符中的代码?

EN

回答 2

Stack Overflow用户

发布于 2018-10-25 10:10:18

如果先更改CalendarItem以静态方式创建它呢?

代码语言:javascript
复制
public class CalendarItem {

    private int type;
    private Task task;
    private Estimate estimate;
    private WorkOrder workOrder;
    private BlockTime blockTime;

    // Change it to private.
    // In the future, we will only create this object through static methods.
    private CalendarItem() {
    }

    public static CalendarItem fromTask(Task t) {
        CalendarItem item = new CalendarItem();
        item.setType(Constants.CALENDAR_TASK);
        item.setTask(t);
        return item;
    }

    public static CalendarItem fromWorkOrder(WorkOrder w) {
        CalendarItem item = new CalendarItem();
        item.setType(Constants.CALENDAR_WORK_ORDER);
        item.setWorkOrder(w);
        return item;
    }

    public static CalendarItem fromEstimate(Estimate e) {
        CalendarItem item = new CalendarItem();
        item.setType(Constants.CALENDAR_ESTIMATE);
        item.setEstimate(e);
        return item;
    }

    public static CalendarItem fromBlockTime(BlockTime b) {
        CalendarItem item = new CalendarItem();
        item.setType(Constants.CALENDAR_BLOCKED_TIME);
        item.setBlockTime(b);
        return item;
    }
    ...
}

如果您可以使用Java Optional或Stream,则可以编写更简洁的代码。(安卓上也有像Lightweight-Stream-API这样的库。)

代码语言:javascript
复制
Disposable disposable = calendarRepository.getCalendar(startDate, endDate)
                .subscribeOn(Schedulers.io())
                .map(calendar -> {
                    List<CalendarItem> calendarItems = new ArrayList<>();

                    // tasks
                    calendarItems.addAll(Optional.ofNullable(calendar.getTasks()).map(it -> it.stream().map(CalendarItem::fromTask).collect(toList())).orElse(emptyList()));

                    // workOrders
                    calendarItems.addAll(Optional.ofNullable(calendar.getWorkOrders()).map(it -> it.stream().map(CalendarItem::fromWorkOrder).collect(toList())).orElse(emptyList()));

                    // estimates
                    calendarItems.addAll(Optional.ofNullable(calendar.getEstimates()).map(it -> it.stream().map(CalendarItem::fromEstimate).collect(toList())).orElse(emptyList()));

                    // blockTimes
                    calendarItems.addAll(Optional.ofNullable(calendar.getBlockTimes()).map(it -> it.stream().map(CalendarItem::fromBlockTime).collect(toList())).orElse(emptyList()));

                    return calendarItems;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(calendarItems -> view.displayCalendar(calendarItems), view::handleError);

如果你只想使用RxJava,你也可以使用下面的代码。(它看起来有点复杂。)

代码语言:javascript
复制
Disposable disposable = calendarRepository.getCalendar(startDate, endDate)
                .subscribeOn(Schedulers.io())
                .map(calendar -> {
                    List<Task> tasks = calendar.getTasks();
                    List<WorkOrder> workOrders = calendar.getWorkOrders();
                    List<BlockTime> blockTimes = calendar.getBlockTimes();
                    List<Estimate> estimates = calendar.getEstimates();

                    List<CalendarItem> calendarItems = new ArrayList<>();

                    // tasks
                    if (tasks != null) {
                        calendarItems.addAll(
                                Observable.fromIterable(tasks)
                                        .map(CalendarItem::fromTask)
                                        .toList()
                                        .blockingGet()
                        );
                    }

                    // workOrders
                    if (workOrders != null) {
                        calendarItems.addAll(
                                Observable.fromIterable(workOrders)
                                        .map(CalendarItem::fromWorkOrder)
                                        .toList()
                                        .blockingGet()
                        );
                    }

                    // estimates
                    if (blockTimes != null) {
                        calendarItems.addAll(
                                Observable.fromIterable(estimates)
                                        .map(CalendarItem::fromEstimate)
                                        .toList()
                                        .blockingGet()
                        );
                    }

                    // blockTimes
                    if (blockTimes != null) {
                        calendarItems.addAll(
                                Observable.fromIterable(blockTimes)
                                        .map(CalendarItem::fromBlockTime)
                                        .toList()
                                        .blockingGet()
                        );
                    }

                    return calendarItems;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(calendarItems -> view.displayCalendar(calendarItems), view::handleError);
票数 1
EN

Stack Overflow用户

发布于 2018-10-25 05:46:39

一种方法是使用更具功能性的样式,如下所示:

代码语言:javascript
复制
.flatMap(calendar -> {
    Observable<CalendarItem> tasks = Observable
        .just(Optional.ofNullable(calendar.getTasks()).orElse(Collections.emptyList()))
        .map(task -> {
            CalendarItem item = new CalendarItem();
            item.setType(Constants.CALENDAR_TASK);
            item.setTask(task);
            return item;
        });

    Observable<CalendarItem> workOrders = Observable
        .just(Optional.ofNullable(calendar.getWorkOrders()).orElse(Collections.emptyList()))
        .map(workOrder -> {
            CalendarItem item = new CalendarItem();
            item.setType(Constants.CALENDAR_WORK_ORDER);
            item.setWorkOrder(task);
            return item;
        });

    // estimates and blockTimes

    return tasks.mergeWith(workOrders).mergeWith(estimates).mergeWith(blockTimes);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52977918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档