Functional Reactive Programming and Bacon
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Title of Series | ||
Number of Parts | 170 | |
Author | ||
License | CC Attribution - NonCommercial - ShareAlike 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this | |
Identifiers | 10.5446/50621 (DOI) | |
Publisher | ||
Release Date | ||
Language |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
|
NDC Oslo 201478 / 170
2
3
5
6
8
11
12
16
21
22
23
27
31
35
37
42
43
45
47
48
49
50
52
54
56
57
58
61
65
66
67
71
74
77
80
81
83
84
85
87
88
89
90
91
94
95
96
97
98
100
102
107
108
112
114
115
116
118
120
121
122
123
126
127
128
130
133
135
137
138
139
140
141
142
143
144
145
147
148
149
150
153
155
156
157
158
159
160
161
162
163
166
169
170
00:00
Functional programmingComputer programmingInformation technology consultingGoogolDifferent (Kate Ryan album)Right angleComputer programmingGoogolParameter (computer programming)Functional programmingSmartphoneLibrary (computing)Multiplication signBitCombinational logicComputer clusterInformation technology consultingMereologyForm (programming)Covering spaceBit rateProgramming paradigmComputer animation
01:52
Bit rateMultiplication signFunctional programmingComputer animation
02:34
Bit rateSlide rulePresentation of a groupFunctional programmingComputer programmingLambda calculusCalculusFunction (mathematics)outputSystem programmingCodeCombinatory logicFunktorCombinational logicLevel (video gaming)ProgrammierstilBit rateFunctional programmingOrder (biology)Parameter (computer programming)Computer programmingInstance (computer science)Electronic mailing listImperative programmingState of matterAdditionSocial classCategory of beingSequenceoutputFunction (mathematics)ResultantAreaCalculusIterationSet (mathematics)Block (periodic table)RecursionProgramming paradigmSoftware testingFreewareWordUsabilityReal numberProgrammschleifeCode refactoringOffice suitePresentation of a groupMappingError messageSound effectConnected spaceDescriptive statisticsHeat transferOcean currentDeclarative programmingCodeStatement (computer science)System programmingReduction of orderMultilaterationData managementBuildingTransformation (genetics)MathematicsExpressionUnit testingMereologyFunktorLambda calculusMaxima and minimaRight angleRootArithmetic meanComputer animation
09:06
System programmingComputer programmingSpreadsheetAnalogySoftware frameworkKeyboard shortcutFunctional programmingAbstractionSequenceFrame problemCodeType theorySound effectEvent horizonSpacetimeComputer programmingPropagatorGraph (mathematics)Discrete groupSequenceSummierbarkeitDifferent (Kate Ryan album)Analytic continuationNumberFunctional programmingMultiplication signTupleoutputCategory of beingData typeSound effectProgramming paradigmMultiplicationAnalogyState of matterTheoryNatural numberUser interfaceBitSystem programmingBlock (periodic table)BuildingSoftware frameworkKeyboard shortcutSpreadsheetConnectivity (graph theory)CodeDataflowMereologySemantics (computer science)Classical physicsWater vaporCellular automatonPerfect groupMathematicsDemo (music)Metropolitan area networkSocial classType theoryLevel (video gaming)CountingInstance (computer science)Integrated development environmentAbstractionInteractive televisionWeb browserComputer animation
15:38
CodeString (computer science)CodeFunctional programming10 (number)Event horizonoutputStreaming mediaCategory of beingLevel (video gaming)Combinational logicObject-oriented programmingType theoryInitial value problemElement (mathematics)NumberWhiteboardLine (geometry)Right angleMathematicsValue-added networkPower (physics)Data managementProcess (computing)Constructor (object-oriented programming)
17:51
Line (geometry)ResultantFunctional programmingDifferenz <Mathematik>Metropolitan area networkImplementationCodeSummierbarkeitCombinational logicDifferent (Kate Ryan album)1 (number)Computer clusterComputer animation
19:59
Semantics (computer science)Event horizonSource codeComputer programmingLibrary (computing)Event horizonFunctional programmingExtension (kinesiology)Different (Kate Ryan album)ResultantImplementationSequenceCategory of beingStreaming mediaMultiplication signString (computer science)Semantics (computer science)State observerSocket-SchnittstelleObject-oriented programmingMetreWeb 2.0CASE <Informatik>MathematicsLevel (video gaming)Limit (category theory)Interior (topology)Classical physicsElectronic mailing listCodeScripting languageDesign by contract2 (number)Process (computing)System callWebsiteMetropolitan area networkProgramming paradigmSpywareInstance (computer science)Computer animation
23:08
Projective planeoutputComputer programmingLink (knot theory)State of matterEnterprise architectureOpen setView (database)CodeLibrary (computing)Bit rateSoftware frameworkMorley's categoricity theoremPrisoner's dilemmaFunctional programmingComputer animation
24:32
Software frameworkStreaming mediaEvent horizonJava appletFunctional programmingBus (computing)Computer programmingStreaming mediaCombinational logicCategory of beingEvent horizonState of matterLibrary (computing)Reverse engineeringDisk read-and-write headMereologyContext awarenessSoftware frameworkFormal languageDifferent (Kate Ryan album)Template (C++)CASE <Informatik>ResultantEndliche ModelltheorieValue-added networkGame controllerObject-oriented programmingNatural numberMathematicsCuboidLie groupSampling (statistics)Computer animation
28:18
Hacker (term)Bit rateHill differential equationPulse (signal processing)Modulare ProgrammierungQuery languageData miningElectric currentPort scannerComputer networkFrame problemSource codeData modelCompilation albumElectronic data interchangeBit rateArtificial lifeBeat (acoustics)Streaming mediaMappingEvent horizonMetreCategory of being2 (number)Graph (mathematics)Computer clusterPulse (signal processing)Goodness of fitMultiplication signCodeNumberConnectivity (graph theory)Functional programmingLevel (video gaming)MathematicsObject-oriented programmingComputer programmingDivisorPoint (geometry)Personal area networkQuicksortEndliche ModelltheorieOcean currentComa BerenicesFood energyModulare ProgrammierungRight angleClassical physicsComputer animationMeeting/Interview
35:45
Electronic data interchangeQuery languageFrame problemWide area networkBeat (acoustics)Exponential functionEmpennagePulse (signal processing)Modulo (jargon)Modulare ProgrammierungMultiplication signPulse (signal processing)CurvatureGraph (mathematics)ResultantStreaming mediaPredicate (grammar)IterationCodeEvent horizonBeat (acoustics)Type theoryNP-hardBit rateDefault (computer science)Level (video gaming)BitDifferent (Kate Ryan album)Mathematics2 (number)Functional programmingOperator (mathematics)Line (geometry)TrailWebsiteSoftware testingMappingIncidence algebraShared memoryComputer-assisted translationCuboidInstance (computer science)Connectivity (graph theory)Logic gateComputer animation
42:49
Pulse (signal processing)Electronic data interchangeFrame problemComputer networkLine (geometry)Query languageWalsh functionBit rateElectric currentoutputCompilation albumSynchronizationBit rateStreaming mediaCategory of beingMultiplication signPulse (signal processing)Parameter (computer programming)NumberType theorySign (mathematics)Keyboard shortcutLimit (category theory)RoutingAttribute grammarMereologyoutputMedical imagingSoftware testingBeat (acoustics)Extreme programmingRight angleDefault (computer science)Level (video gaming)Total S.A.Boss CorporationComputer programmingOpen sourceFunctional programmingBitValue-added networkModulare ProgrammierungElectronic mailing listBoolean algebraLine (geometry)Source codeEvent horizonElement (mathematics)Bus (computing)Predicate (grammar)Computer animation
49:53
Frame problemBit ratePulse (signal processing)Functional programmingComputer programmingComplex (psychology)Key (cryptography)Natural numberState of matterComplex (psychology)CodeCartesian coordinate systemWechselseitige InformationBuildingIntegrated development environmentFunctional programmingComputer programmingMeeting/InterviewComputer animation
50:45
Perturbation theorySpeicherbereinigungEvent horizonTwitterSemiconductor memoryLeakFood energySource codeBit rateFlash memoryDot productComputer animation
52:20
Denial-of-service attackCASE <Informatik>Bit rateComputer animation
53:01
AreaBuffer overflowCoefficient of determinationComputer animation
Transcript: English(auto-generated)
00:02
Let's get started. Welcome to my little talk about functional reactive programming. There are many great talks on functional programming here on NDC, so I won't cover that in much detail, but we will see about the combination with functional reactive
00:23
programming. Note, I will be using JavaScript in this talk. It's not necessary to use JavaScript with functional reactive programming, obviously it's a paradigm and a mindset and more or less pretty much agnostic to language.
00:41
So we will cover functional reactive programming and bacon. There will be a lot of bacon in many different sizes, forms, shapes, and maybe some surprises. First, this is me. My name is Michael.
01:01
I work at BEC Consulting in Trondheim here in Norway, and I use Google a lot. I often say that I have never lost an argument since 2007 when the smartphone came out, and Google is partly to thank for that.
01:21
I love bacon, both the meat and the functional reactive library. And let's get to know me a bit better. This is me. I am not the most photogenic guy, but I like seeing myself large.
01:48
Also, if we are to get real personal, this is my heart rate right now. Don't worry, I am a professional, I have seen a doctor, but it's quite high.
02:05
The doctor said I have a heart of a top athlete, but I obviously didn't look like one and didn't have the body of one. My heart, at least, functions quite well.
02:22
If it peaks, I think, 180, 190, maybe even 200, then it would be time to call an ambulance. I might have a heart attack. During this presentation, you will see my heart rate right up there, to see when I
02:41
screw up, when I say something wrong, or just possibly flat lines, I don't know. You can follow my heart rate live at bit.ly and to see heart rate. So there is maximum connections of hundreds. I think it should do it for us, but you can also follow from home, if that's what you like.
03:10
Let's see. In this talk, we will cover functional programming. Just as I said, introductory, just the basics, just short abbreviated descriptions of it.
03:25
We will cover reactive programming, functional reactive programming, and bacon.js. We will get back to that later. When and where to use functional reactive programming and some code.
03:40
Functional programming. What is it? It stems or has roots from lambda calculus, where we operate with mathematical functions or mathematical expressions without names. In programming, we usually call them anonymous functions.
04:01
In functional programming, as with lambda calculus, we often use recursion. Let's see some amazing GIFs for how you can feel while doing functional programming. You feel really powerful with a little amount of code.
04:22
Some buzzy words for you. It's a first-class, higher-order function we operate with in functional programming. It is a declarative, stateless side-effect-free, and immutable paradigm. Let's see what declarative means.
04:41
It is. Instead of detail-oriental programming, we use a more declarative and more descriptive programming style. Instead of using Fs and Ls and for loops that we would do in the opposite or the antonym of declarative or imperative programming,
05:04
we can use something like for-each and map and so on. We'll get also back to that. Stateless side-effect-free. We have the notion of pure functions. Given inputs, we always have the same output.
05:22
There's not any state in a function. There is no side-effect from running a function. A function running this side, this part of the system, can't alter the behavior of a separate function without using that value.
05:43
No matter the system state, no matter what horizontally aligned state, we have the same output of a function given its input. The system relies solely on input, no external state.
06:03
Immutable values are values when one is set, you can't override or alter those values. Instead of, for instance, looping over a list and transforming every item in the list and returning the same list with the transformed values,
06:22
return a new list with the new transformed values. With the functional programming, we write small manageable fragments of code. As its small building blocks of code and all values are immutable, we have highly reusability and they are testable.
06:43
As we have the notion of pure functions, as I talked about, they are testable because we can't just have unit tests by passing in some inputs and knowing what the values or the result of the execution will be. We achieve functional programming by using functors and combinators.
07:04
Functors are transforms from one category into another category. For example, the use of combinators like map. Combinators are higher-order functions that allow those to piece together logic. Examples of this are map, that's a combinator here.
07:23
We're mapping over a sequence of one, two, three, and the result will be every item multiplied by two. It's a new list returned with the transformed values.
07:43
Another example we have is reduce. Reduce, I figure many know both what maps and reduce are. By the way, are there any real experiences with functional programming in here?
08:03
Quite some. Reduce, we take, we get a function with a first parameter as the result of executing this function, previous iteration, and the second argument will be the current item that you're in when iterating over it.
08:25
This can be used, for instance, like here, where we always take the addition of the previous execution and the current item. The result will be six. You can also use something like reduce to drive map from it by iterating over it
08:44
and not reducing the original value but returning a new, concatenating every item. That would be how we would implement map by using reduce.
09:03
We have other building blocks and combinators as well, like filter, combine, fold, write, and we'll see some of them later. Functional programming, no, reactive programming. Let's see what that entails.
09:22
But first, a GIF. It's funny. It's often referred to as dataflow programming. We're having data that propagates through nodes to keep the system updated.
09:44
If I have a value in this side of the system and a dependent of that value over here, and this value changes, this value changes accordingly. That's a horrible explanation, but a classic analogy is spreadsheets.
10:05
We use them all the time. Spreadsheets are the perfect example of reactive data. We have, let's say, the cell A and B, the cell with the sum of A and B. If either A or B changes, the sum will change as well.
10:25
I have a fantastic interactive demo of this. Let's see if it works. This is a graph with data, and when changing it, we see changes propagate through the graph.
10:45
Reactive properties are not an entirely new concept for any of us. Many of the well-used and familiar frameworks like Angular, Ember, Knockout, Reactive, have reactive properties.
11:05
The two-way data binding in Angular are by its nature reactive. Just to motivate you, here's Bacon. We're getting into some more funny bits or fun soon.
11:24
Functional reactive programming. There's not much theory to it. Really, it's just combining, as you'd think, both the functional aspect or the functional paradigm with the reactive paradigm.
11:43
It originally started with Conel, Elliot, and Paul Hidak. I probably mispronounced those names horribly. In 1997, when they introduced a system called FRAN, functional reactive animations, the goal with FRAN was to have a collection of reactive data
12:04
and functions for computing rich UI and animations. Animations changing with the reaction of user inputs, like the mouse moving and the graphical component
12:22
changing its coordinates based on the user input. In functional reactive programming, or classic functional reactive programming, we operate with two primary abstractions. The first one is behaviors, which is like continuous values and events that are discrete.
12:46
Let's see the semantics. As we see, the function of time gives a value. Based on that semantic, we see it's continuous, so it always has a value.
13:01
An example of continuous values would be like height, or the time, or the amount of water in this glass. We always have a value. There's no space in which there are no values. Events, on the other hand, are discrete.
13:21
It's a tuple with time and a value. We know that when they are discrete, we can count discrete occurrences. For instance, a discrete value is the number of people in this room.
13:42
The difference between continuous and discrete values are continuous values must be measured or observed, but discrete values can be counted. In functional reactive programming, we treat events and behaviors as sequences.
14:02
We can use the functional building blocks on reactive data as sequences. We can use map, we can use filter on events, no matter the time or when events or behaviors occur.
14:25
First, let's see why you would be interested in using functional reactive programming. We get functional programming in a naturally stateful environment, like in the browser or with the UIs.
14:40
That relies a lot on state. With that, we get fragmented and dry code and testable code. We can have reactive data types abstracting the state, so I don't have to manually update the state in the GUI.
15:04
With that, we limit the side effects of the UI. It's really good for handling multiple inputs and outputs and handling events across different inputs. OK, that's for the boring theoretical part.
15:24
Now, prepare to be amazed. The amount of self-control for not eating that helmet is amazing to me. To be able to build a helmet out of bacon. OK, remember this. That's probably at least tens of thousands of lines of code, right?
15:48
And asynchronous handling across the board and really unmanageable code. Nope. Thank you.
16:02
Let's see the code. We have this behavior. We can create a behavior using bacon and saying as an event stream from the object of it could be a jQuery object, it could be any type of object that has an event listener,
16:23
and listen for the change event. We can map that using the combinator map and get the value of the event that occurs. Two property is just creating a behavior from the event stream. We have an initial value of the value of the element
16:42
and we can make it have a continuous value by just updating the behavior. And we map it as a number. In JavaScript, using number as a function,
17:02
not newing it up as a constructor, we get a primitive value. Number of text string three is exactly equals to three, the primitive value, as opposed to new number of three is not equal three.
17:23
We can use just map to number as an anonymous function. If we wrap this in a function that takes an ID, we can create behaviors from our inputs quite easily.
17:41
Come on! So little code, so much power. That's Kevin Bacon, by the way, for those of you who didn't see that. He may or may not be a recurring theme of this talk. I won't say which.
18:00
We create two nodes, the A and B nodes. These are the nodes on the far left of the example. Everyone remember that? Yep, great. And the D node is the top node also input. But C here is combined of A and B and it's combined with a function subtract.
18:22
So the result of running that line of code would be a new behavior that's a combination of A and B, but is transformed using subtract. So it's the difference between A and B. This can be used to assign to an output
18:41
and combine again with the node D to create the final sum. So that, it's probably about ten lines of code to complete the example there. Any questions of the implementations of this?
19:04
Nope. Kevin Bacon. Okay, we just experienced Bacon.js and it's pretty amazing. For those of you not knowing who this is, let's have it ask the others and raise your hand.
19:24
Who knows who this is? Francis Bacon, yeah. I didn't know. I had to Google him. But it's a well-known philosopher, scientist and writer from England and he is credited as the creator of empiricism.
19:46
Also he is used as a front man for Bacon.js by the creator of Bacon.js. Some Finnish guy I can't pronounce the name of. The semantics of Bacon.js
20:03
comes from classic functional reactive programming. And classic functional reactive programming is referred to as the original with Paul Heideck and Connell Elliott. So we have the notion of both the behaviors and events.
20:20
This is opposed to something like, for instance, reactive extensions that just have the notion of observables. There's no real distinction. But you can easily use something like reactive extensions to achieve what I'm showing you as well. There are many different implementations of functional reactive programming libraries
20:43
in like C sharp, Java, Objective-C and much. And of course JavaScript. In Bacon.js we have a different terminology. A behavior is called a property and events are called event streams.
21:02
To create reactive data we wrap them using something like from event target as we've seen. And we also have from promise taking in just either an A star compliant promise implementation
21:22
or something like the deferred of jQuery. We can send in an Ajax request from jQuery using that and when the result comes the event target will trigger. We also have from callback and more. From callback is just what you think it is
21:41
from a callback, an asynchronous callback. From event target doesn't limit itself to click events or change events from jQuery. As long as it has an event listener it could be an event meter from node, it could be web sockets or anything really DOM, clear DOM objects.
22:04
Let's see some examples using Bacon. Here we start a new event stream sequentially. Every 100 millisecond go over this list of ints.
22:21
Then we map it to characters using the anonymous function string from character code. Map to upper case and concat strings and the result will be after 300 milliseconds NDC. A bit less contrived example maybe but this is a property of a checkbox.
22:45
We have a property representing a checkbox every time it checks or checks we update the value and we can use that in many different ways as we will see later. Prepare yourself is one sexy cabin.
23:04
Bacon.js is even cooler than this guy I think. But when and where could we use it or should we use it? Do we have to have like this small functional projects
23:23
with no enterprise code or can we use it in everyday projects? This is a technology radar we in back publishes and it's our current view of the state of the technology
23:43
especially here in Norway. Marked in red is functional reactive programming it's hard to see but it's categorized as consider to use in your project. It's assessed as something you can use
24:01
and should probably use if you have many inputs and outputs that you need to handle in a way that's functional. Really, that didn't come out well. Okay.
24:22
You can see the radar using this link or open.back.no or radar.back.no. Functional reactive programming or bacon.js in particular can be easily combined with other existing frameworks or libraries.
24:41
Even though you have this big framework handling all your JavaScript like React or Backbone you can still use bacon for the part that needs this care. This is an example using React.
25:02
We create a bus. A bus is just a manual event stream that we can push values to. We create an empty event stream and we can push values to it. The label stream is a new event stream transformed from the original event stream
25:21
but with the text reversed. In React we can use this in this way. Just pass the event streams to the component and render it. If we push value to the text stream
25:40
React can update. You probably need to have set states when a value on the event stream changes. This is an example using Backbone. This could be somewhere in your initialize or refactoring its own method.
26:04
Starting a new event stream from a button that is called NewToDo. This is just syntactic sugar on top of jQuery for bacon. When on NewToDo,
26:21
and as NewToDo is immutable and is triggered, and can be used again, we have the combination of the title property or the title behavior and the checkbox behavior. The result of combined templates
26:42
will be an object literal and sampled by the click of NewToDo. If you see on the value generated it would be an object literal with the values of the title and of the checkbox. Obviously, it is just passing it
27:04
to a collection create and we create a new model on Backbone. That is all we need to do really. Functional Reactive Programming should be used
27:20
when you need to manage a lot of events and state. I am not saying you have to use, but that is the case when it is most prominent. It is used already, functional reactive programming is used
27:41
in different context implementations, as I said, in many different languages. Netflix uses it in their APIs to handle states. There is one hearting, I think, to wrap your head around functional programming if you have
28:01
no functional programming experience. That could be just making it harder to get started with. To illustrate that, Kevin Bacon. Let us hack on my heart rate
28:23
and do some live coding. Let us hope everything works out. There we are.
28:45
I have not brought up my notes. The first thing we need to do, everyone can see this, I guess. In the back.
29:02
It should be clear. I have this module that is connected to Heart Rate Monitor right here, through Bluetooth Low Energy. It is publishing up to pusher.com
29:22
and distributed on to what I hope is hundreds of people home. We can connect this quite easily by doing from event targets and using channel.
29:41
As I said, you can use any event emitters. The event is data. Now we can see if we do log, and refresh. I have the data there.
30:01
We see it is a string, so we need to map it to a number. First, we need to map and get the value. As we see, it is an object literal with a value. We can map that using this. This is the same as doing something like map from x.value.
30:25
It is just a shorthand. Map it as a number. Logging this, we should see just a number logged out. We don't.
30:41
There we are. If we return this from this function, we can use it here. I am requiring it here. Beats per minute is the behavior,
31:01
or rather, event stream for my heart rate. We can use it to make a graph. We have beats per minute chart,
31:21
which we can append a value to, like so. This just takes
31:40
the value every time we see it and appends it to the graph. Let's see how that works. Not too good. Get time.
32:01
We should see the graph updating automatically. Of course, there is some code handling the graph, but that is not really that relevant here. As it is immutable values, we can use it again without it having changed, so we can map it to our property,
32:23
or a behavior in classic functional programming terminology, and assign the value to a text node using a method text. This should update the current heart rate here.
32:42
Is it clear what is happening here? We are making it into our property, so it is a continuous value, and we are assigning the value to a DOM node that is called textBeatsPerMinute. We use the function text,
33:01
so it is a shorthand, or a convenience syntactic sugar for doing text, like so, and value. If I want to transform the value
33:20
and use it in different ways, we can see that. I have this component, and I can take components and beats from beatsPerMinute. This should return a pulse,
33:40
but we will have to implement it first. This is the function we are calling with the component beatsFrom. It takes beatsPerMinute in, and I will have to get up my cheat sheet, because there is math in here,
34:02
and that is hard to do. Now I have the beatsPerMinute as a stream. I have probably 143. I don't think that is healthy, but that is another discussion.
34:20
I need to transform it into a stream that ticks every time my heart beats. I will need the interval of every time a heart beats. Using the magic of math, we can use beatsPerMinute
34:44
and using the bounds, it may be it every 10 seconds, and then taking that
35:00
and mapping it to the math apart, around 60 divided by, like so, and times 1000. That looks good.
35:20
If I had 80 in my heart rate, totally unrealistic, but it is the easiest math I can do. 60 divided by 80 would be 0.75, I think.
35:42
That means my heart takes every 750 milliseconds. This interval behavior, or rather event stream, should be an event stream with the interval of when my heart beats.
36:01
Does that make sense? Yes. I need to convert that into an event stream that has a value every time my heart beats. Now I have the interval of it, but I need to convert it to,
36:21
I want a value 1 every time my heart beats. We can use something like this.
36:42
Great. Thank you. I would love to say it was a test, but no. That flatMap latest bacon interval. What this does is it,
37:04
my style is totally red. FlatMap creates a new event stream based on the function that is given. FlatMap latest is just that with the latest value it gets. The result of this will be what we are after.
37:22
A tick every time our heart beats. I am mapping it directly to true just to have a true value every time it beats. We can use this, for instance, to, let's say,
37:41
if I want to have, we can return this, return heart beats, like so. In main, we can use pulse and filter is checked.
38:03
Like so. Is checked is from this, is what we saw earlier, just a behavior of the checkbox. Now we see we can use filter on the pulse. Everyone knows what filter does. It takes a predicate and based on that predicate
38:21
we can choose what iterations or what values to take. The result is only take pulse when the checkbox is checked. With that value, on value, we want to play a sound.
38:42
Like so. Let's hope that works. Yeah. That is my heart rate. When doing this at home, I also had a heart rate of 110
39:00
because I stood up from the couch. Let's turn it off. It is disturbing. We can also use these heart beats to create a graph of every time my heart beats.
39:20
Like a flat liner type of graph. What is it with a graph that shows the text? We have the default value of zero and when my heart beats, we have a value of one. We need to create that flat line first.
39:41
We take interval and every 50 milliseconds we have the value zero. This is our base event stream. We merge heart beats and map to two.
40:00
The two is just for making the graph look prettier. I have done this before. I know it requires two. Let's convert this to our behavior with the default value of zero. Now we have this behavior
40:21
that is zero when my heart is not beating and one or two when it is beating. To draw it in a graph, we use the same code as previously on value. And X to...
40:41
Do I have... I have not. Beats chart. Chart beats. And I need the charts from wherever.
41:07
I am in components. Back lib chart. That is a hard character type. Charts.
41:21
Like so. Now I create the chart by doing so. We can append a value with new dates. Get time. And giving X.
41:41
Like so. Let's try that out. That works. And we can even do this. You see the lag there? Every ten seconds it updates.
42:03
I couldn't really find a way to make the math work by having the difference between the updating of the values. If that makes any sense. Let's turn it off. Now we have a pretty working health monitor.
42:27
As this suggests, we can do better. Let's try to communicate with WebRTC to take a picture every time my pulse gets...
42:41
I was a bit optimistic setting the default value of 120. I think we can bump that. Let's see.
43:00
I have created this easy WebRTC module. It just uses a bacon bus like this manual event stream and pushing our image every 500 milliseconds. It is an event stream of images taken.
43:20
We need to have this predicate used to filter when my pulse is over a given value. Let's do that. We use what was seen previously. Combine with like so.
43:51
The function combined over is A and B. Let's have a new line.
44:02
I am a bit disturbed by the talk about seven habits that every programmer makes. My argument list is terrible. I am sorry about that. Every time A is over or equal to B.
44:20
Combine from the beats per minute and combine with the property from BPN input. That is this input. That is a property or a behavior. This will be a property that is true
44:43
every time my heart rate is over a given limit. We can use this to make a picture. Filter pulse is over something. This is my picture like this.
45:05
Return picture equals value. Any other mistakes I made?
45:26
I appreciate you saying it. It wasn't intended as a rude comment. Let's draw the picture.
45:43
Of beats per minute, like so. This should work, shouldn't it? We are forgetting to use the picture. We have the behavior of the pictures or event stream of the picture but we are not assigning it to anything.
46:04
Assign to test image using the attribute source. Make sense?
46:29
Let's see if that works.
46:40
Now it is obviously a lot of pictures because my heart rate is insanely high. Wait for it.
47:03
I will just turn this down. It is easier. That seems like a bad idea. There, another picture. Exercise for the day.
47:21
154. Fine, we can also do we have some time so we can make this a bit better. Like only showing the input if picture is allowed or WebRTC is allowed picture.
47:43
Map as boolean. Make it a property with a default value of false and assign that to test image again
48:00
but this time use the method toggle. That makes sense now knowing what we know about functional reactive programming and bacon, doesn't it? We map the picture as a boolean if the picture is null or undefined or whatever
48:22
we get a false value and a true value otherwise. The default is false. Assign that to test image. Toggle. We can hide the picture until we allow
48:40
and the first value gets emitted. We can also do the same with allowing with the allow bar. Now we see the input shows even though I haven't allowed
49:00
we can hide that using RTC because that emits value even though my heart rate is not over given value, right? So doing the same thing map as boolean to property false and assign that to element
49:26
input type number and toggle. Like so. There it's hidden until I allow
49:42
and then it's still... Oh, there it is. So now I can use this. Okay. That went fairly well I think.
50:00
Let's move on. Kevin Bacon. And some key takeaways from this. I'm just going to stop doing this. Making my Mac laggy. Functional reactive programming gives us functional programming in a naturally stateful environment.
50:24
It lets us build complex applications fragment by fragment with testable code and reusable code, obviously. We use immutable values also for easy reuse and it avoids a lot of spaghetti code.
50:44
Also, Bacon has been the theme and this hot fellow, Kevin Bacon. So any questions about this? Any comments? Yeah.
51:18
But events that are done often send an end event
51:23
and then collect that. So once an event source is ended Bacon will stop emitting values and hopefully garbage collect. But there is a possibility of not necessarily memory leaks but using a lot of memory with it.
51:47
I have five minutes left. Any other questions? Okay. Feel free to ping me at Twitter.
52:01
Also, if you want to connect your Bluetooth low energy heart rate monitor up to Node just github.com slash I can show you, it sits here.
52:28
Node heart rate. Like so. And it is as easy as it is. And you can constantly monitor your heart rate
52:42
in case you are in danger of dying. Just like me. Yeah. Thank you.
53:05
Good talk, dog.