将项目的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();
        }
}

最佳答案

经过一番思考,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;
}

07-24 15:49