Previous Lecture Complete and continue  

  Observable - example

Topics Covered

  • Convert an input field to an Observable using fromEvent
  • Operate over values using .map()
  • Debounce our Observable chain using .debounceTime()

Overview

We can use Observable to wrap async events that happen more than once compared toPromises. The composition of Observables are a great way to declare how we way our async data flow to be without having to deal manage it ourselves.

Convert an input field to an Observable usingfromEvent

An input field is a great example of values that happen over time. When a user types in values we’re able to convert the input event that is emitted by the element into an Observable where we’re able to perform operations on it’s values.

Operate over values using .map()

Observable also allows for operators to on values that were emitted. We can change the shape of these values and return them into our chain.

Debounce our Observable chain using.debounceTime()

Another great operator allows us to delay receiving values down our chain. It’s a common pattern to manage or limit the values that go through our chain.

Example Code

index.html

<input>
	

app.js

var $ = document.querySelector.bind(document);
var myInput = $('input');
var obs = Rx.Observable.fromEvent(myInput, 'input');
obs.subscribe(function(event) {
  console.log(event.target.value);
});
	
var $ = document.querySelector.bind(document);
var myInput = $('input');
var obs = Rx.Observable.fromEvent(myInput, 'input');
obs
.debounceTime(200)
.map(function(event) {
  return event.target.value;
})
.subscribe(function(value) {
  console.log(value);
});
	

6 comments