RxJava-通过输入流发送对象

时间:2018-10-19 06:47:07

标签: java rx-java

我有Observable<Person>和来自外部库sendByStream(InputStream inputStream)的方法

我想输入我的输出流

final PipedOutputStream pipedOutputStream = new PipedOutputStream();
final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);

使用我的可观察对象并将其发送到此外部方法。我不知道如何以非阻塞方式进行操作,因为sendByStream(InputStream inputStream)正在阻塞。

我尝试将Observable转换为Completable,在doOnNext中写入流,并使用方法doOnCompleted关闭并发送流,但是首先填充完全传递管道,然后通过方法发送。

我应该为sendByStream方法打开另一个线程,还是有一种方法可以使用rxJava风格?

我现在所拥有的(非常幼稚的暗示,但是可以正常工作):

try {
    PipedOutputStream pipedOutputStream = new PipedOutputStream();
    PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
    new Thread(() -> {
        facade.sendByStream(pipedInputStream);
        try {;
            pipedInputStream.close();
        } catch(final IOException e) {
            e.printStackTrace();
        }
    }).start();

    return persons.
        .doOnNext(p -> {
            try {
                pipedOutputStream.write(p.getBytes());
            } catch(final IOException e) {
                LOGGER.error("Problem with writing to output stream");
            }
        })
        .toCompletable()
        .doOnCompleted(() -> {
            try {
                LOGGER.info("Closing output stream");
                pipedOutputStream.close();
                LOGGER.info("output stream closed");
            } catch(IOException e) {
                LOGGER.error("Problem with closing output stream");
            }
        })
        .doOnCompleted(() -> LOGGER.info("Sending file completed"));
} catch(final IOException e) {
    return Completable.error(RuntimeException::new);
}

0 个答案:

没有答案
相关问题