how to chain Cmd Msgs

后端 未结 1 1614
清酒与你
清酒与你 2021-01-04 07:17

I have a list of Cmd Msgs that need to be run in order. I\'m currently using Cmd.batch list but it seems like all of them are running simultaneousl

相关标签:
1条回答
  • 2021-01-04 07:42

    Task.sequence will ensure that the tasks run in sequence rather than simultaneously.

    To make a Cmd msg from a task, you use Task.attempt or Task.perform.

    Edit

    Based on your updated question, I don't think there is a real need to use Tasks for this. It sounds like you want to chain a bunch of updates together, and that can be done by having the update function call itself recursively. You could use List.foldl to accumulate the model state and commands for each subsequent message.

    Here's a quick and dirty example of what I mean:

    update msg model =
      case msg of
        ChainMsgs msgs ->
          let
            chain msg1 (model1, cmds) =
              let (model2, cmds1) = update msg1 model1
              in model2 ! [ cmds, cmds1 ]
          in
            List.foldl chain (model ! []) msgs
        _ ->
          { model | message = model.message ++ ", " ++ toString msg } ! []
    

    You are guaranteed that the messages are passed to update in the correct order, because there's no need to wrap it in tasks which makes order of execution ambiguous.

    Here is a gist of this quick 'n dirty example which you can paste directly into http://elm-lang.org/try:

    0 讨论(0)
提交回复
热议问题