Many loopsLesson 22 of 23

Where does a component get what it needs?

Give a component its dependencies from outside, and swap them without touching it.

This component greets whoever types their name. Something has to produce the greeting, and it might be a table of phrases, a translation service or a fake in a test. The component shouldn't care which.

Predict

Read init, update and view in WelcomeNoDeps. None of them mentions English or Spanish. Press Greet in your head: which greeting appears, and which line of the file decided that?

Check your answer

Hello, Ada!, and the last line decided it: Layer.provide(Greeter.english).

update only says Greet.make({ name }). That is a Command, a description of work, and the description doesn't say who does the greeting.

Try it

  1. Press Greet and read the log: SubmittedName, the Greet Command, then CompletedGreet with the text. Which of those rows would differ in Spanish?

  2. Change Greeter.english to Greeter.spanish in the last line. Before you run: which other lines have to change?

  3. Add a third way to build the service, one that takes its time, and provide it. Before you press Greet: the button will read "Greeting…" for a second. Who wrote that, and when?

static readonly formal = Layer.succeed(
  Greeter,
  Greeter.of({
    greet: (name) =>
      Effect.sleep("1 second").pipe(
        Effect.as(`Good day to you, ${name}.`)
      )
  })
)
  1. A test wants a greeter that answers at once with a fixed string. What would it provide, and to which of the two exports?

About steps 3 and 4

You didn't write it for this change. h.isRunning(Greet) was in the view all along. It had nothing to show while the greeter answered instantly.

The test would provide its own Layer to WelcomeNoDeps. That is why the file exports the component twice: once as written, asking for Greet, and once with the app's Layers already given.

What you found

This is lesson 5 again, with a component where the program was. There, a program asked for a service and received it from a Layer, and you swapped the Layer without touching the program. Here Greet is a Command.Service: it declares its args and the message it ends in, and its Layer attaches the body and picks up the Greeter. The component asks for Greet. Component.provide gives it one, for itself and everything below it.

Nothing was added to learn. A component states what it needs and gets it from outside, so the same update and view run against a real service, a slow one or a fake.

That leaves a component with a pure update, effects that are values and dependencies that come from outside. How do you know it works?

22
Principle 22

The same idea at every size

A component names the services it needs and receives them from a Layer, exactly as a program does. Nothing new to learn, one level up.

ResultStarting

No messages yet

Use the example above. Each message that reaches update shows here, with what it changed.