Skip to content
This repository has been archived by the owner on Feb 23, 2022. It is now read-only.

flatMap vs switchMap usage for side effects #105

Open
MFlisar opened this issue Jan 12, 2020 · 1 comment
Open

flatMap vs switchMap usage for side effects #105

MFlisar opened this issue Jan 12, 2020 · 1 comment
Labels
question Further information is requested

Comments

@MFlisar
Copy link

MFlisar commented Jan 12, 2020

You use switchMap for all your side effects, so e.g. if you consider an UpdateSideEffect that triggers e.g. 3 actions and we want those actions to always be executed after each update, we need to use flatMap instead like following:

 fun UpdateSideEffect(companion: Companion, clazz: Class<Action>): SideEffect<State, Action> = { actions, state ->
    actions
            .ofType(clazz)
            // flatMap, because we never want to "lose" any side effect action!
            .flatMap {
               
                Observable.just(item)
                        .flatMap {
                            Observable.fromArray(
								Action1,
								Action2,
								Action3
							)
                        }
            }
}

If we call e.g. 3 update actions, we will only get the side effects of the last action (if we use switchMap), but we will get all side effect actions if we use flatMap like in my example. Of course, if order of side effect actions is important we could also use concatMap as well...

Question
I'm unsure why you don't use flatMap by default, is there any particular reason for that? Or is there something speaking against using flatMap at this position instead at all?

@Tapchicoma Tapchicoma added the question Further information is requested label Jan 22, 2020
@Tapchicoma
Copy link
Contributor

Using flatMap would be fine if your side effect does not consume actions that it emits, new input action does not happen with higher frequency then sideeffect actions emission. TL;DR use flatMap if you know why you are doing it.

switchMap should be used by default as it more fail safe in cases when sideeffect triggered again, while still running from previous input.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
question Further information is requested
Development

No branches or pull requests

2 participants