The Elm Architecture

So, what is Elm? And what is more interesting, The Elm Architecture?

Elm is a statically typed, pure functional programming language, which is compiled to Javascript and runs in Web Browser.

The Elm Architecture(TEA) is an approach to building web applications, with several key aspects:

Unidirectional dataflow

Immutable state

Managed side effects

If you are familiar with javascript libraries like Redux or Cycle.js, you will find many similar concepts and even term names, and this is not a coincidence, because Redux state management pattern is actually inspired by the Elm Architecture

The core concept of TEA really boils down to only three core types (or classes in OOP) and three functions:

Model (aka State in Redux) — this is the type for describing the state of your app or screen. From now on, I will refer it as State, because this better expresses what it is used for, as the term Model has so many definitions and has became very bloated.

Msg (short for Message, aka Actions in Redux) — base type for all events happening during interaction with UI (such as button click, text inputs, etc)

Cmd (short for Command) — type for side-effects. If you create Cmd, that means you want to execute a particular side effect (http request or other blocking IO operation). When executed, the command will return new Msg with resulting data.

Function Update (aka reduce in Redux) — function Update takes Msg and State as input, and returns a pair of two values — new State and Cmd, or simply speaking, what side effect you want to execute for incoming Msg. The main aspect of this function is that it is a pure function. That means there must be no side effects inside this function.

Function View (aka render in Redux) — takes State as an input, and renders view (HTML in case of Elm) in declarative manner. I will name this function in Redux manner, as the term View is already heavily used in Android Framework.

Function Init — here we define our initial values for State, and, if necessary, return first Cmd, for initial HTTP request for example.

And this is basically all you need to know about The Elm Architecture!

Don’t be confused by the ‘architecture’ word. As an Android dev you can see TEA as Design Pattern which can be implemented in presentation layer, or simply speaking in your presenter

The best way to learn new things is to examine them by example. Let’s take a look into at a simple login screen, with input fields for login and password, and a button for sending http request. The following code snippets will be in Kotlin language, as this post is primarily addressed to Android Developers.