从RxJava 1到RxJava 2

时间:2016-11-01 01:47:13

标签: java rx-java

我正在尝试将此RxJava1代码转换为RxJava2

public static Observable<Path> listFolder(Path dir, String glob) {
    return Observable.<Path>create(subscriber -> {
        try {
            DirectoryStream<Path> stream =
                    Files.newDirectoryStream(dir, glob);

            subscriber.add(Subscriptions.create(() -> {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            Observable.<Path>from(stream).subscribe(subscriber);
        } catch (DirectoryIteratorException ex) {
            subscriber.onError(ex);
        } catch (IOException ioe) {
            subscriber.onError(ioe);
        }
    });
}

问题是在Rxjava2中我没有让订阅者添加新的订阅。

1 个答案:

答案 0 :(得分:5)

享受RxJava 2简洁(Flowable现在是背压支持课程):

public static Flowable<Path> listFolder(Path dir, String glob) {
    return Flowable.using(
        () -> Files.newDirectoryStream(dir, glob),
        stream -> Flowable.fromIterable(stream),
        stream -> stream.close());
}

如果您不想要背压,请将Flowable替换为Observable