Organize Code in the Main and Effect Functions

André Staltz
InstructorAndré Staltz
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 6 years ago

We need to give structure to our application with logic and effects. This lessons shows how we can organize our code into two parts: main() function for logic, and effects functions for effects.

[00:01] We still have our app working here with a timer. It has two parts. It has logic and effects. We need to give some structure to this. It's not generic at the moment. For instance, it only supports one type of effect, which is writing to the DOM.

[00:15] First, we need to make a function here to contain our logic. We can put our logic in a function called main, for instance. It's where our application lives, and it just returns the stream which is later subscribed to.

[00:29] We can do something similar with the DOM effect. We can put that in a function called DOM driver. It takes the text stream as input, and it just subscribes to that text stream. Basically, our main is describing logic, and our DOM driver is describing how to perform an effect, given some data.

[00:55] We need to call these functions in order to make something happen. First, we call main. That will create a stream. We're going to give that name, sink. Then I'm going to pass sink to the DOM driver, like this. Then it's going to work just like before, nothing really fundamentally changed.

[01:14] Why did I call it a sink? It's because it's a destination. Just like in a kitchen sink, it's where water goes to, and it doesn't come back. Here, we have our logic or data is going to this return value. It's going to this sink, and it's not coming back. That's the idea behind it.

[01:34] We have some structure now, but let's say we want to have more types of effects, such as for instance, we want to make a console log effect. We just need to do a similar type of function here. We can call that the log driver.

[01:47] It takes a message stream as input, and we can just subscribe to that. Then every time we get a message, we can put that in the console like that. Then we just need to also pass the sink to the log driver.

[02:10] Now, let's run this and see if it works. We need to open the console, and there we see both of the types of effects happening at the same time. The DOM is being written, and the console is being written as well.

[02:22] In general, you want to put each effect in a different driver, and these are separated from your application.