RxJS 5 - function called twice

660 views Asked by At

I'm trying to show a confirmation Modal, before deleting a line using RxJS.

  • The code below works fine if I delete 1 line.
  • When I delete a second line, then deleteLineFulfilled is called 2 times.
  • If I delete a third line, then deleteLineFulfilled is called 3 times and so on...

Any idea why?

const deleteLineEpic = (action$, store) =>
action$.ofType(DELETE_LINE_REQUEST)
    .flatMap((action) => Observable.merge(
                Observable.of(showModalYesNo('CONFIRM_DELETE')),
                action$.ofType(MODAL_YES_CLICKED).map(() =>
                    deleteLineFulfilled(action.line)
                )
                .takeUntil(action$.ofType(MODAL_NO_CLICKED))
           ));
2

There are 2 answers

2
Olaf Horstmann On BEST ANSWER

action$ is a perpetual observable, and it will only stop when an action of the type MODAL_NO_CLICKED is dispatched - from your code it's hard to say when that happens, you should add an .take(1) before the .takeUntil(...).


However with this architecture you have to make sure that there has to be either an MODAL_YES_CLICKED or MODAL_NO_CLICKED emitted and that the emission cannot be skipped.

A simpler way would be to implement the confirm-dialog, subscribe to the result and then only dispatch the delete-action if the result was YES and if the result was NO don't even dispatch the action. That way you'll have a much cleaner action-epic.

0
Dada On

Try with this:

        .first() // $action is a perpetual observable. Only take the first one.
        .takeUntil(action$.ofType(MODAL_NO_CLICKED))