Mobius: On the EffectHandler, what is the difference between Transformers, Consumers, Actions and Functions?

Viewed 171

On the EffectHandler, what is the difference between Transformers, Consumers, Actions, and Functions? I see that the 4 types are supported in the docs:

ObservableTransformer<Effect, Event> rxEffectHandler =
    RxMobius.<Effect, Event>subtypeEffectHandler()
        // Effect Handlers can be an ObservableTransformer
        .addTransformer(Effect.SearchRequest.class, this::handleSearchRequest)
        // They can also be a Consumer<F> (eg. Consumer<ShowErrorMessage>)
        .addConsumer(Effect.ShowErrorMessage.class, view::showErrorMessage, AndroidSchedulers.mainThread())
        // Or an Action
        .addAction(Effect.SomethingElse.class, this::handleSomethingElse)
        // Or a Function<F, E> (eg. Function<SaveToDb, Event>)
        .addFunction(Effect.SaveToDb.class, this::handleSavingToDb)
        .build();

which one to use to use? Maybe I am missing some RxBackground that I need to read up on first?

2 Answers

The type signatures of each give you a hint, but a rough summary is: - Consumer F -> (): Gets the effect object as an argument and calls something as an effect. Example: Toast.makeText(context, effect.message(), duration).show();

  • Action () -> (): Same as consumer but you don't need anything from the effect object. Example: context.startActivity(new Intent(MyActivity.class))

  • Function F -> E: Blocking transformation from effect to a new event. Can be used if you know exactly one event will be emitted and you can safely do it as a blocking call. Example: return Event.lookupResult(repository.get(effect.key()))

  • Transformer Observable<F> -> Observable<E>: The most powerful API, a full rx that can do anything to transform a stream of effects to a stream of events, including emitting more than one event per effect or even emitting events without receiving an effect first. Example: effects.flatMap(effect -> return loadData(effect.uri())).map(Event::dataLoaded) (edited)

Here is how each of these work,

╔═════════════╤═══════════════════════════╤═════════════════════╗
║     Type    │  Receives effect object?  │ Can produce events? ║
╠═════════════╪═══════════════════════════╪═════════════════════╣
║ Action      │            No             │         No          ║
║ Consumer    │            Yes            │         No          ║
║ Transformer │            Yes            │         Yes         ║
╚═════════════╧═══════════════════════════╧═════════════════════╝
Related