第一:这是我使用RxJ的第一个项目,我认为我会通过使用它学习得最好。
我找到了这个答案:Turning paginated requests into an Observable stream with RxJs
但是它在评论中说:
You're exceeding the maximum call stack still. At around 430 pages returned. I think recursion might not be the best solution here
我想查询Youtube Data API,结果返回到页面中,我需要对它们进行分页。
我以为这样的工作流程可以工作:
1)发起通话
2)检查响应是否具有“nextPageToken”
3)如果有,请再次向Youtube API发出请求
4)如果没有,请完成
So to do this I could Imagine the following Observables / streams:
FirstRequestStream -A-X--------------->
ResponseStream -A-A-A-A--X-------->
RequestStream -I-A-I-A----------->
A = Action
I = Info from upper stream
X = Termination
(不确定此图是否与我的制作方法相符)
因此,ResponseStream依赖于FirstRequestStream和RequestStream(使用合并功能)。 RequestStream依赖于ResponseStream(这称为循环可观察的吗?)
-这是正确的方法吗?
-“传播可观察物”是好事,甚至可能吗?(我在创建一个可观察物时遇到问题)。
-我应该先尝试其他方法吗?
-是否可以创建相互依赖的可观察流?
感谢您的帮助。
最佳答案
您使这个问题过于复杂,可以使用defer运算符轻松解决它。
想法是您要创建延迟的可观察对象(因此将创建它,并且仅在订阅后才开始获取数据),并使用相同的可观察对象将其连接,但对于下一页,该对象也将与下一页连接,依此类推。 。所有这些都可以不递归地完成。
代码如下:
const { defer, from, concat, EMPTY, timer } = rxjs; // = require("rxjs")
const { mergeMap, take, mapTo, tap } = rxjs.operators; // = require("rxjs/operators")
// simulate network request
function fetchPage(page=0) {
return timer(100).pipe(
tap(() => console.log(`-> fetched page ${page}`)),
mapTo({
items: Array.from({ length: 10 }).map((_, i) => page * 10 + i),
nextPage: page + 1,
})
);
}
const getItems = page => defer(() => fetchPage(page)).pipe(
mergeMap(({ items, nextPage }) => {
const items$ = from(items);
const next$ = nextPage ? getItems(nextPage) : EMPTY;
return concat(items$, next$);
})
);
// process only first 30 items, without fetching all of the data
getItems()
.pipe(take(30))
.subscribe(e => console.log(e));
<script src="https://unpkg.com/rxjs@6.2.2/bundles/rxjs.umd.min.js"></script>
关于pagination - RxJs可观察到的分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254323/