scaladiode

Handling of Future.failure in a Diode effect


In Diode, how do one handle a Future.failure in an effect? The doc (https://ochrons.github.io/diode/usage/Effects.html), it is clear how a success value from the Ajax call is used to update the model with a Pot.Ready, but I wonder how one can catch a failure and update a Pot.Failed instead.


Solution

  • With plain effects, you need to transform both successful Future and a failed Future into a suitable action using a combination of map and recover. For example:

    val eff = Effect(Ajax.get(url)
      .map(r => NewMessages(r.responseText)))
      .recover { case e => MessageLoadingFailed(e.getMessage) }
    )
    

    If you are using AsyncAction (or the derived PotAction) it provides a helper method effect that automatically handles future failure and creates a PotFailed state.