gpt4 book ai didi

java - 将 RxJava Emissions 写入文本文件的有效方法?

转载 作者:行者123 更新时间:2023-11-30 07:42:47 25 4
gpt4 key购买 nike

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;
}

关于java - 将 RxJava Emissions 写入文本文件的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com