[英]Effective Way to Write RxJava Emissions to Text File?
What is the most effective way to write an Observable<T>
of items into a text file, where a line is written for each emission? 将项目的Observable<T>
写入文本文件的最有效方法是什么,其中每次发射都要写一行? I am using a try-with-resources
setup below with a CountDownLatch
, but it definitely feels like an anti-pattern due to the blocking. 我在下面使用带有CountDownLatch
的try-with-resources
设置,但是由于阻塞,它的感觉绝对像是反模式。 There is also a strong possibility of interruptions and early unsubscriptions throwing errors. 中断和提早退订引发错误的可能性也很大。
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();
}
}
After a second thought, Observable.using()
is perhaps not the best candidate here. 经过一番思考, Observable.using()
可能不是此处的最佳选择。 I would try simply something like this (with finallyDo()
instead): 我会尝试这样的事情(用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.