RxJS - ajayupreti/Tech.Blogs GitHub Wiki
This Blog is to introduce RxJS. The ReactiveX library for JavaScript. RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.
Observable: represents the idea of an invokable collection of future values or events.
var button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click')
.subscribe(() => console.log('Clicked!'));
We do not care about the other values entered by the user, just need to get the value of the press Enter event and respond. At this point we only need to filter this Observable:
import { Observable } from 'rxjs'
const $input = <HTMLInputElement>document.querySelector('.todo-val')
const input$ = Observable.fromEvent<KeyboardEvent>($input, 'keydown')
.filter(r => r.keyCode === 13)
.do(r => console.log(r))
const app$ = input$
app$.subscribe()
In order to accomplish turning the text in the input box into a to-do item, we need to get the value in input and turn it into a todo-item node. This process is a typical map of the process.
import { Observable } from 'rxjs'
const $input = <HTMLInputElement>document.querySelector('.todo-val')
const input$ = Observable.fromEvent<KeyboardEvent>($input, 'keydown')
.filter(r => r.keyCode === 13)
const app$ = input$
.map(() => $input.value)
.filter(r => r !== '')
.do(r => console.log(r))
app$.subscribe()
After you create this item, we give them to add their own event listener to complete click on a to-do item, make it into the finished state functions, and can only add new eventListener out after the creation of these item. So this process is the process of Observable <= = map => Observable => merge. There is an operator in RxJS that can do this map and merge in one step:
//emit 'Hello'
const source = Rx.Observable.of('Hello');
//map to inner observable and flatten
const example = source.mergeMap(val => Rx.Observable.of(`${val} World!`));
//output: 'Hello World!'
const subscribe = example.subscribe(val => console.log(val));