Chain http request and merge json response in ELM

倾然丶 夕夏残阳落幕 提交于 2019-12-07 15:05:30

The way to fire off two concurrent requests is to use Cmd.batch:

init : ( Model, Cmd Msg )
init =
    ( initialModel, Cmd.batch [ fetchLSLeaders, fetchRSLeaders ] )

There is no guarantee on which request will return first and there is no guarantee that they will both be successful. One could fail while the other succeeds, for example.

You mention that you want to merge the results, but you didn't say how the merge would work, so I'll just assume you want to append the lists of leaders together in one list, and it will be useful to your application if you had only to deal with a single RemoteData value rather than multiple.

You can merge multiple RemoteData values together with a custom function using map and andMap.

mergeLeaders : WebData (List Leader) -> WebData (List Leader) -> WebData (List Leader)
mergeLeaders a b =
    RemoteData.map List.append a
        |> RemoteData.andMap b

Notice that I'm using List.append there. That can really be any function that takes two lists and merges them however you please.

If you prefer an applicative style of programming, the above could be translated to the following infix version:

import RemoteData.Infix exposing (..)

mergeLeaders2 : WebData (List Leader) -> WebData (List Leader) -> WebData (List Leader)
mergeLeaders2 a b =
    List.append <$> a <*> b

According to the documentation on andMap (which uses a result tuple rather than an appended list in its example):

The final tuple succeeds only if all its children succeeded. It is still Loading if any of its children are still Loading. And if any child fails, the error is the leftmost Failure value.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!