将RxJava排放写入文本文件的有效方法?

时间:2015-12-22 23:21:11

标签: java reactive-programming rx-java

Observable<T>个项目写入文本文件的最有效方法是什么,其中为每个发射写入一行?我在下面使用try-with-resources设置CountDownLatch,但由于阻止,它肯定感觉像反模式。中断的可能性很大,而且早期取消订阅会导致错误。

 private void saveToCSV(String url) {

        CountDownLatch latch = new CountDownLatch(1);

        File outputFile = new File(url);

        try(BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

            writer.write(ReportItem.getHeaders() + "\r\n");

            reportItems.forDate(dt)
                    .map(ReportItem::toCSVLine).map(s -> s.concat("\r\n"))
                    .subscribe(Checked.a1(writer::write), Throwable::printStackTrace, latch::countDown);

            latch.await(); 

        } catch (Exception e) {
            e.printStackTrace();
        }
}

1 个答案:

答案 0 :(得分:1)

经过一番思考,Observable.using()可能不是这里的最佳候选人。我会尝试这样的事情(改为使用finallyDo()):

private void saveToCSV(String url) {
    BufferedWriter writer = getBufferedWriter(url);
    writer.write(ReportItem.getHeaders() + "\r\n");
    reportItems.forDate(dt)
               .map(ReportItem::toCSVLine).map(s -> s.concat("\r\n"))
               .finallyDo(() -> close(writer))
               .subscribe(Checked.a1(writer::write), Throwable::printStackTrace);
}

private void close(BufferedWriter writer) {
    try {
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private BufferedWriter getBufferedWriter(String url) {
    try {
        File outputFile = new File(url);
        return new BufferedWriter(new FileWriter(outputFile));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}