RxJS & Redux-Observable

What is RxJS

RxJS

Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators.

透過 Observable 組合各種非同步行為的 Library

Observable

Design Pattern

Observer Pattern

Iterator Pattern

Observer Pattern

function clickHandler(event) {
  console.log('user click!');
}

document.body.addEventListener('click', clickHandler)

Iterator Pattern

(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 }

Observerable

Obserable Example

RxJS Example

Redux-Observable

RxJs 5-based middleware for Redux. Compose and cancel async actions to create side effects and more

Action Side Effect

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: 想避免連續的查詢?  

By Using Redux-Obserable

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))
        );

How to work ?

How to work ?

常用情境

連續非同步 - 通知訊息

避免高觸發 - 無限滾動文章

訊息通知

export const openToast = () => ({
  type: OPEN_TOAST,
});

export const openToastEpic = action$ => {
  return action$
       .ofType(OPEN_TOAST)
       .delay(3000)
       .mapTo({ type: CLOSE_TOAST });
}

Email 即時驗證

無限滾動文章

Marble Diagram

Marble Diagram

Observable.interval(10)
  .take(3)
  .map(x => x + 1)
  .filter(x => x % 2 === 1)

Try it!

Why Marble Diagram?

1.模擬非同步測試​​

  • 情境複雜不好模擬,且容易出錯
  • 出錯時不知道要找誰

2. 精確非同步測試

  • 測試會花過多時間

By Using Marable Diagram for Testing

Conclusion

需處多個非同步之間的優化時,會考慮使用

Made with Slides.com