I have a function that gets executed at certain intervals with some data. Something similar to a polling function:
function poll(handler) {
setInterval(handler, 1000); // Mocking network communication
}
So I want to use that function in a redux-observable
epic like this (pseudocode to follow):
action$
.filter(...)
.map((action) => poll)
.map(results from poll)
How can I subscribe to the polling function and use rxjs?
EDIT:
What I've tried but it's failing
function start() {
return Rx.Observable.create((observer) => poll(observer.next));
}
function startProcess(action$) {
return action$
.filter((action) => action.type === 'START_PROCESS')
.map((action) => start())
.swipWhile((result) => result !== 'proceed') // I only want to dispatch the next action after we get a `proceed` result from the polling function
.map(() => ({ type: 'CAN_START_PROCESS' })
}
I could wrapp the poll
function into a promise, and then using Rx.Observable.fromPromise
but I'd like to do it the reactive way.
答案 0 :(得分:2)
我建议你做的是写一个poll函数来返回一个observable:
function createPoll$() {
return Rx.Observable.interval(1000)
.flatMap(makeRequest);
}
您的启动过程功能如下:
function startProcess(action$) {
return action$
.filter((action) => action.type === 'START_PROCESS')
.switchMap(createPoll$)
.filter(result => result === 'proceed')
.map(() => ({ type: 'CAN_START_PROCESS' })
}
答案 1 :(得分:0)
好的,我让它将观察者绑定到自身:
function start() {
return Rx.Observable.create((observer) => poll(observer.next.bind(observer));
}
但是仍然不知道使用已经创建的运算符是否有更好的解决方案。