etiennelenhart / Eiffel

Redux-inspired Android architecture library leveraging Architecture Components and Kotlin Coroutines
MIT License
211 stars 14 forks source link

Feature - Ability to add custom interceptions to the targeted builder #116

Closed jordond closed 5 years ago

jordond commented 5 years ago

In Interceptions.Builder there is a add function that allows adding custom interceptions using the DSL. I have just added these functions to the Interceptions.Targeted.Builder as well.

This allows you to write custom Interception's, and extension functions for them like:

// SampleInterception.kt

...

fun <S : State, A : Action> Interceptions.Builder<S, A>.sample(
    debugName: String = "",
    sample: (state: S, action: A) -> A
) = apply { add(Sample(debugName, sample)) }

inline fun <S : State, A : Action, reified T : A> Interceptions.Builder.Targeted<S, A, T>.sample(
    debugName: String = "",
    crossinline sample: (state: S, action: T) -> A
) = apply { 
    add(Sample(debugName) { state, action -> if (action is T) sample(state, action) else action }) 
}

// SampleViewModel
val interceptions = interceptions<SampleState, SampleAction> {
    sample { state, action -> ... }

    on<SomeAction> {
        sample { state, someAction -> ... }
    }
}
etiennelenhart commented 5 years ago

I didn't add those myself since this looks a bit misleading to me:

on<SomeAction> {
    sample { state, someAction -> ... }
}

It would suggest that Sample is only invoked on SomeAction like the other built-in targeted interceptions, although it only works in conjunction with the if (action is T) statement and is actually invoked on every action.

Maybe we could come up with some type of base class, like TargetedInterception that takes care of the conditional invocation, although it might get ugly without reified types…