rxJava - Obropable如何从.create方法体中发出?

时间:2016-02-16 06:18:42

标签: java rx-java reactive-programming

我正在查看以下从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)) ?

1 个答案:

答案 0 :(得分:1)

因为DirectoryStream实现Iterable会迭代目录中的条目,并且Observable.from(Iterable)将序列转换为发出序列中的项目的Observable,这是条目中的条目目录。然后,当订阅者订阅Observable时,它将接收正在发出的项目。

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

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

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