rxjs - 在 RxJs 中进行一些操作后,有没有办法将子属性合并回父源?
问题描述
我有一个运算符,它对源的子属性执行一些递归操作。完成递归操作后,如何将子属性合并回源?
const state = {
posts: [
{id: 3, title: 't1', userId: 1},
],
index: 0,
config: {
previousBufferSize: 1,
nextBufferSize: 1,
}
};
const source = new BehaviorSubject(state);
const generatePreviousPosts$ = (posts) => {
return Observable.create(observer => {
getPost(posts[0].id - 1)
.then(previousPost => {
observer.next([previousPost, ...posts]);
});
});
};
const previousBuffer$ = source.pipe(
pluck('posts'),
expand(generatePreviousPosts$),
tap(console.log),
// What do I do to merge post back in the state so I could use takeWhile?
takeWhile(state => {
const {posts, config, index} = state;
return posts.length <= config.previousBufferSize - index + posts.length &&
posts[0].id != null;
})
);
解决方案
https://github.com/Dorus在 rxjs gitter 上提供了一个更优雅的解决方案。
const shouldGetPost = ({posts, config, index}) => posts.length <= config.previousBufferSize - index + posts.length
&& posts[0].id != null
const generatePreviousPosts = ({posts, config, index}) => !shouldGetPost({posts, config, index}) ? EMPTY :
from(getPost(posts[0].id - 1)).pipe(
map(previousPost => ({[previousPost, ...posts], config, index}))
)
const previousBuffer$ = source.pipe(
expand(generatePreviousPosts)
);
推荐阅读
- php - PHP MongoDB 找出返回更大尺寸的查询
- javascript - Firebase:不可见的 reCaptcha 在 React JS 中不起作用
- c++ - 在 C++ 中输出枚举类类型的向量元素
- python - TPU:NameError:定义 Keras 自定义 train_step 时未定义名称“_minimize”
- ruby-on-rails - 无法创建评论应用。部署后退出代码不是 0
- ajax - 在 Flask 中接收带有 request.files 和 request.form 的文件
- javascript - 进度条不适用于 javascript 和 bootstrap
- laravel - 如何在 Laravel 中更改名称上带有 id 的 url 地址?
- python - 具有相同参数名称的多重继承
- reactjs - 无法在反应导航中删除现有参数