繁体   English   中英

rxJava-.create方法的主体如何发出Observable?

[英]rxJava - How Observable can emit from the body of .create method?

我正在查看以下来自GitHub的示例,该示例显然有效,但我不明白为什么:

Observable<String> fsObs = CreateObservable.listFolder(
                Paths.get("src", "com", "alex", "experiment"),
                "*.java")
                .flatMap(path -> CreateObservable.from(path));

// CreateObservable.listFolder
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);
            }
        });
    }

请注意,正在创建Observable.<Path>from(stream).subscribe(subscriber) 此行如何将消息发送到flatMap(path -> CreateObservable.from(path)) ?

因为DirectoryStream实现了Iterable ,它将对目录中的条目进行迭代,并且Observable.from(Iterable)将序列转换为Observable,从而发出序列中的项目,即目录中的条目。 然后,当订户订阅Observable时,它将接收正在发射的项目。

Observable.<Path>from(stream).subscribe(subscriber)的简化版本是:

for (Path path : stream) {
    subscriber.onNext(path);
}

调用subscriber.onNext是如何发射数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM