Commands and Subscriptions
The Elm Architecture is neat, but how do you interact with the world?! I want random numbers! What time is it? How do I send HTTP requests?
I have not made a big deal about it, but so far all of our programs were created with
Browser.sandbox. We gave an initial
Model and describe how to
You can think of
Browser.sandbox as setting up a system like this:
We get to stay in the world of Elm, writing functions and transforming data. This hooks up to Elm’s runtime system. The runtime system figures out how to render
Html efficiently. Did anything change? What is the minimal DOM modification needed? It also figures out when someone clicks a button or types into a text field. It turns that into a
Msg and feeds it into your Elm code.
By cleanly separating out all the DOM manipulation, it becomes possible to use extremely aggressive optimizations. So Elm’s runtime system is a big part of why Elm is one of the fastest options available.
In the next few examples, we will instead create programs with
Browser.element. This will introduce the ideas of commands and subscriptions which will allow us to interact more with the outside world.
You can think of
Browser.element as setting up a system like this:
Like before, you get to program in the nice Elm world, but these
Sub values can tell the runtime system to generate random values, ask about the current time, make HTTP requests, etc.
I think commands and subscriptions make more sense when you start seeing examples, so let’s do that!
Note 1: Some readers may be worrying about asset size. “A runtime system? That sounds big!” It is not. In fact, Elm assets are exceptionally small when compared to React, Angular, Vue, etc.
Note 2: We are going to use packages from
package.elm-lang.orgin the upcoming examples. We have already been working with a couple:
But now we will start getting into some fancier ones:
There are tons of other packages on
package.elm-lang.orgthough! So when you are making your own Elm programs locally, it will probably involve running some commands like this in the terminal:
elm init elm install elm/random elm install elm/http
That would set up an
I will be mentioning the packages we are using in the following examples, so I hope this gives some context on what that is all about!