Chapter 2. Core FRP


This chapter covers

  • Stream and Cell types
  • map, merge, hold, snapshot, filter, lift, never, and constant primitives
  • Forward references with StreamLoop and CellLoop
  • Making an accumulator with hold and snapshot

To demonstrate the core principles of FRP, in the first few chapters of this book we’ll use our Sodium library in Java. We chose Java because it has static typing (which works well with FRP), and the syntax turns out to be quite nice. We’re trying to teach the concepts of FRP, not the implementation details of specific systems. We designed Sodium to embody those basic concepts as minimally and completely as possible. Sodium and Java are just a convenient vehicle for this purpose; we hope you won’t see this book as specific to a language or FRP system.

In later chapters, we’ll delve into other FRP systems and languages. FRP systems are all the same conceptually, but the design and naming can differ.

2.1. The Stream type: a stream of events

FRP is based on two classes or data types. The example in chapter 1 used cell, and now we’re going to look at its counterpart, stream. Recall the following:

  • Cells—represent a value that changes over time
  • Streams—represent a stream of events

Figure 2.1 shows an example: a window with a text field and a button. You can type text into the field, and when you click the button, the text field is cleared.

Figure 2.1. When you click Clear, the text you entered disappears.

2.2. The map primitive: transforming a value

2.3. The components of an FRP system

2.4. Referential transparency required

2.5. The Cell type: a value that changes over time

2.6. The merge primitive: merging streams

2.7. The hold primitive: keeping state in a cell

2.8. The snapshot primitive: capturing the value of a cell

2.9. Looping hold and snapshot to create an accumulator

2.10. The filter primitive: propagating an event only sometimes

2.11. The lift primitive: combining cells

2.12. The never primitive: a stream that never fires

2.13. Referential transparency dos and don’ts

2.14. FRP cheat sheet

2.15. Summary