LoginSignup
4
2

More than 5 years have passed since last update.

RxJS6のカスタムオペレータを作るのが簡単なので、redux-observableで利用する

Last updated at Posted at 2018-10-02

RxJS6でpipeオペレータが使えるようになったことで、カスタムオペレータを作るのも簡易になった。

上記にある通り、例えば既存のオペレータをまとめる程度であればこのぐらい簡単にできると例示されている。

/**
 * You can also use an existing operator like so
 */
const takeEveryNthSimple = (n: number) => <T>(source: Observable<T>) =>
  source.pipe(filter((value, index) => index % n === 0 ))

redux-observableで使ってみる

例えばよく使うtapでconsole.logに表示してignoreElementsで消すというのはよくやるデバッグの手段だろう

export const pingEpic = (action$) =>
  action$.pipe(
    ofType("PING"),
    tap(console.log),
    ignoreElements()
  )

今回はこれをカスタムオペレータとして置き換えてみるとこうなる

const debug = () => <T>(source: Observable<T>) =>
  source.pipe(
    tap(console.log),
    ignoreElements()
  )

export const pingEpic = (action$) =>
  action$.pipe(
    ofType("PING"),
    debug()
  )

オペレータはObservableを受け取ってObservableを返せば良い。例示に併せて、ここでは関数化している。debugが関数を返す関数になっているので、例えばtapに渡す値を変更できるようにしたいならこういう具合だろう

const debug = (tapFn = console.log) => <T>(source: Observable<T>) =>
  source.pipe(
    tap(tapFn),
    ignoreElements()
  )

export const pingEpic = (action$) =>
  action$.pipe(
    ofType("PING"),
    debug(item => console.log("This is DEBUG => ", item))
  )
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2