Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators.
透過 Observable 組合各種非同步行為的 Library
Observer Pattern
Iterator Pattern
function clickHandler(event) {
console.log('user click!');
}
document.body.addEventListener('click', clickHandler)
(Lazy evaluation)
const arr = [1, 2, 3];
const iterator = arr[Symbol.iterator]();
iterator.next();
// { value: 1, done: false }
iterator.next();
// { value: 2, done: false }
iterator.next();
// { value: 3, done: false }
iterator.next();
// { value: undefined, done: true }
RxJs 5-based middleware for Redux. Compose and cancel async actions to create side effects and more
export function fetchSearchResult () {
if (!keyword) {
return;
}
dispatch({ type: SEARCH_REQUEST }); // loading animation
return fetch(`/search?k=${keyword}`).then(res != {
dispatch(receiveSearchResult());
dispatch(replace('/searchResultsPage'));
dispatch(addKeywordHistory(keyword)); // store keyword
});
}
More: 想避免連續的查詢?
export const searchEpic = action$ =>
action$
.ofType(SEARCH_REQUEST)
.filter(action != action.payload)
.switchMap(getSearchResult)
.mergeMap(res =>
Observable
.of(
receiveSearchResult(res.data),
push(`/search/${res.keyword}`),
addSearchHistory(res.keyword))
);
export const openToast = () => ({
type: OPEN_TOAST,
});
export const openToastEpic = action$ => {
return action$
.ofType(OPEN_TOAST)
.delay(3000)
.mapTo({ type: CLOSE_TOAST });
}
Observable.interval(10)
.take(3)
.map(x => x + 1)
.filter(x => x % 2 === 1)
Try it!