Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md#build-your-own-operators-easily

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

/**
 * 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))
  )
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした