【发布时间】:2015-07-07 16:37:15
【问题描述】:
我对@987654321@(以及一般的响应式范式)很陌生,所以请多多包涵。
假设我有这个News 和这个嵌套的Comment 数据结构:
public class News {
public int id;
public int[] commentIds; //only top level comments
public News(int id, int[] commentIds) {
this.id = id;
this.commentIds = commentIds;
}
}
public class Comment {
public int id;
public int parentId; //ID of parent News or parent comment
public int[] childIds;
public Comment(int id, int parentId, int[] childIds) {
this.id = id;
this.parentId = parentId;
this.childIds = childIds;
}
}
假设我有这个 API 端点:
getComments(int commentId) //return Observable<Comment> for Comment with ID commentId
现在,让我们假设:
getComments(1); //will return Comment(1, 99, [3,4])
getComments(2); //will return Comment(2, 99, [5,6])
getComments(3); //will return Comment(3, 1, [])
getComments(4); //will return Comment(4, 1, [])
getComments(5); //will return Comment(5, 2, [])
getComments(6); //will return Comment(6, 2, [])
**
现在,如果我有News n = News(99, [1,2]),我如何递归地获取它的所有子评论?即获取 ID 为 [1,2,3,4,5,6] 的 cmets?
**
我搜索并偶然发现了这个:https://jkschneider.github.io/blog/2014/recursive-observables-with-rxjava.html
这是递归函数:
public class FileRecursion {
static Observable<File> listFiles(File f) {
if(f.isDirectory())
return Observable.from(f.listFiles()).flatMap(FileRecursion::listFiles);
return Observable.just(f);
}
public static void main(String[] args) {
Observable.just(new File("/Users/joschneider/Desktop"))
.flatMap(FileRecursion::listFiles)
.subscribe(f -> System.out.println(f.getAbsolutePath()));
}
}
它展示了如何进行递归 observable 调用的示例,但内部函数 (f.listFiles()) 是一个阻塞操作(不返回另一个 Observable)。在我的例子中,内部函数 (getComments) 是一个非阻塞函数,它返回另一个 Observables。我该怎么做?
任何帮助将不胜感激。
【问题讨论】:
-
你错了 -
listFiles确实返回了Observable。 -
嘿,你是对的!我怎么可能没有意识到这一点?好的,那我该如何实现这个......嗯......
-
哦,我的意思是 内部函数
f.listFiles(),它不会返回可观察值,对吧?返回 observable 的是FileRecursion::listFiles。还是我在这里错过了什么? -
你是对的——那个是
File#listFiles,它返回File[]。
标签: java reactive-programming rx-java observable