A program is a valueLesson 7 of 23

What if the answers keep coming?

Describe values that arrive over time, and what happens when you stop listening.

An Effect produces one value and is finished. numbers produces three. ticks produces one every 200 milliseconds and never finishes.

Predict

ticks goes on forever, and it's defined right there in the file. When you press Run, does this program ever end?

Check your answer

Yes, at once, after Got 1, Got 2 and Got 3.

It's lesson 1 a third time. ticks is a description of a clock, and nobody ran it. program only uses numbers. Defining a Stream, like defining an Effect, makes nothing happen.

Try it

  1. In program, replace numbers with ticks, and add Stream.take(5) on the line before runForEach. Before you run: when is the last line printed? (The clock's first tick comes at once.)

  2. Something stopped that clock after five ticks. To see it, add a line to the end of the ticks pipe: Stream.ensuring(Effect.log("Stream closed")). Before you run: does it print, and when?

  3. Change take(5) to take(2). When does Stream closed print now? Who decided that?

  4. Imagine the program without take. It would tick forever. From the last lesson, what could still end it?

About steps 3 and 4

take(2) decided, from outside the clock. The Stream ended because the code using it had enough, and its cleanup ran at that moment. You never wrote the line that stops a timer.

Without take, whoever runs the program can still interrupt it, as race interrupted the slow download, and the cleanup runs then too.

What you found

A Stream is a description of many values and of when they come. Stream.map changes each one (it's how ticks turns a clock into a count), Stream.take says when to stop, and Stream.runForEach turns the whole thing into an ordinary Effect that does something for each value and finishes when the Stream does.

Everything from the earlier lessons carries over, because a Stream is a value too. You build it from smaller pieces. You change it from outside. And whoever runs it can stop it, at which point whatever it opened is closed for you: a timer, a socket, a file.

That last part is easy to miss and it matters later. Listening to something has a start and an end, and with a Stream you only describe the middle.

The values so far were numbers you made up. Data from a server, a file or a form arrives with no guarantees at all. Before a program can trust it, something has to answer a plain question: what shape is the data?

07
Principle 7

Values over time are a value too

A Stream describes many values and when to stop. Opening it and closing it are the runtime's job.

OutputNot run yet

Not run yet

Read the code and say what it will do. Then press Run.