gpt4 book ai didi

java - 从 RxJava 1 到 RxJava 2

转载 作者:搜寻专家 更新时间:2023-11-01 02:21:31 27 4
gpt4 key购买 nike

我正在尝试将此 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 中,我没有让订阅者向它添加新订阅。

最佳答案

享受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

关于java - 从 RxJava 1 到 RxJava 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40353058/

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