【发布时间】:2023-03-26 08:00:01
【问题描述】:
我正在使用 Bacon.js 学习 FRP,并希望将来自分页 API 的数据组装到流中。
使用数据的模块有这样的消费API:
// UI module, displays unicorns as they arrive
beautifulUnicorns.property.onValue(function(allUnicorns){
console.log("Got "+ allUnicorns.length +" Unicorns");
// ... some real display work
});
每次获取新数据集时,组装数据的模块都会从 API 和 pushes 请求顺序页面到流上:
// beautifulUnicorns module
var curPage = 1
var stream = new Bacon.Bus()
var property = stream.toProperty()
var property.onValue(function(){}) # You have to add an empty subscriber, otherwise future onValues will not receive the initial value. https://github.com/baconjs/bacon.js/wiki/FAQ#why-isnt-my-property-updated
var allUnicorns = [] // !!! stateful list of all unicorns ever received. Is this idiomatic for FRP?
var getNextPage = function(){
/* get data for subsequent pages.
Skipping for clarity */
}
var gotNextPage = function (resp) {
Array.prototype.push.apply(allUnicorns, resp) // just adds the responses to the existing array reference
stream.push(allUnicorns)
curPage++
if (curPage <= pageLimit) { getNextPage() }
}
我如何订阅流,以便为我提供曾经收到的所有独角兽的完整列表?这是flatMap 还是类似的?我不认为我需要一个新的流出来,但我不知道。对不起,我是 FRP 思维方式的新手。需要明确的是,组装数组是可行的,感觉就像我没有做惯用的事情。
我没有为此使用 jQuery 或其他 ajax 库,所以我没有使用 Bacon.fromPromise
您可能还想知道为什么我的消费模块想要整个集合而不是增量更新。如果它只是附加行可能没问题,但在我的情况下,它是一个无限滚动,它应该在以下情况下绘制数据:1. 数据可用和 2. 区域在屏幕上。
【问题讨论】:
标签: javascript frp bacon.js