Note that version

The following example is based on the syntax of the latest [email protected] official RxJS version 6

< script SRC = "https://cdn.bootcdn.net/ajax/libs/rxjs/7.3.0/rxjs.umd.js" > < / script >

The core concept

  • Observable Observable
    • On behalf of a groupIn the futureforthcomingThe event object(Method of observation)
  • Observer
    • Represents a receiver[Observation results]Object (received isThe event object)
    • The observer object is an object that contains three properties containing callback functions (Next, Error, complete).
  • Subscription object
    • Represents the individual executing Observable/Observer (which can be used to unsubscribe)
  • Operators operator.
    • Must have aThe functional programmingPure function properties (functions with no side effects) as defined in
    • Mainly used to deal with a series ofObject method collection
    • Common options include map filter concat flatMap switchMap…

Functional Programming

5 plus 6 minus 1 times 3Copy the code

We package each operation into different functions, and use these functions to combine the results we want. This is the simplest Functional Programming.

const add = (a, b) => a + b
const mul = (a, b) => a * b
const sub = (a, b) => a - b

sub(add(5, 6), mul(1, 3))
Copy the code

readability

[9, 4] concat () [8, 7] / / merge sort () / / sorting filter (x = > > x 5)Copy the code

High maintainability

For features such as Pure function, execution results are independent and do nothing to the external environment, making Functional Programming better for debugging and unit testing.

Easy parallel/parallel processing

ForEach

var arr = ['Jerry', 'Anna'];

for(var i = 0; i < arr.length; i++) {
	console.log(arr[i]);
}
Copy the code

A DOM click

javascript

document.addEventListener('click'.(ev) = > {
    console.log(ev)
})
Copy the code

RxJS

// Get the fromEvent method
const { fromEvent } = rxjs;
Subscribe to the click event
const clicks$ = fromEvent(document.'click').subscribe(console.log);
// Unsubscribe
clicks$.unsubscribe()
Copy the code

Limit DOM clicksev.clientX < 1000

const { fromEvent } = rxjs
const { filter } = rxjs.operators

var clicks$ = fromEvent(document.'click')
var subs$ = clicks$.pipe(filter(ev= > ev.clientX < 1000)).subscribe((x) = > console.log(x))
Copy the code

Three limit DOM clicksev.clientX < 1000And take the first three

const { fromEvent } = rxjs
const { filter, take } = rxjs.operators

var clicks$ = fromEvent(document.'click')
var subs$ = clicks$.pipe(
    filter(ev= > ev.clientX < 1000),
    take(3)
).subscribe((x) = > console.log(x))
Copy the code

Three limit DOM clicksev.clientX < 1000And take the first three

const { fromEvent } = rxjs
const { filter, take } = rxjs.operators

var clicks$ = fromEvent(document.'click')
var subs$ = clicks$.pipe(
    filter(ev= > ev.clientX < 1000),
    take(3)
).subscribe((x) = > console.log(x))
Copy the code

Four limit DOM clicksev.clientX < 1000Select only the last click if the interval between the first three clicks exceeds 800

const { fromEvent } = rxjs
const { filter, take, debounceTime } = rxjs.operators

var clicks$ = fromEvent(document.'click')
var subs$ = clicks$.pipe(
    debounceTime(800),
    filter(ev= > ev.clientX < 1000),
    take(3)
).subscribe((x) = > console.log(x))
Copy the code

Timing output

Copy the code
// Get the interval method
const { interval } = rxjs
// Take the take operator
const { take } = rxjs.operators

/ / the subscribe subscribe
interval(1000).pipe(take(4)).subscribe(console.log)
Copy the code

Infinite scrolling list

#infinite-scroller {height: 500px;width: 700px;border: 1px solid #f5ad7c;overflow: scroll;padding: 0; }li {padding : 10px 5px;line-height: 1.5; }li:nth-child(odd) {background : #ffe8d8; }li:nth-child(even) {background : #f5ad7c; }Copy the code
<ul id="infinite-scroller"></ul>
Copy the code
/** * prefix * map: Maps the incoming data stream, similar to the map of an array. * Filter: Similar to the array filter, filters the incoming data stream. Pairwise: Returns an array of the current emitted value and the previous emitted value. * startWith: The returned Observable emits the supplied observable value before emits the source Observable value. * haustmap: new values are emitted only when the internal Observable is complete. * /

 /** * Step * 1 getQuotesAPI - Returns the URL of the API that uses the current page number as the query parameter. * 2 processData - Processes the data returned by the FETCH API and adds the current page number. * 3 renderNews - Receives each piece of news data and renders it to the page. * 4 isUserScrollingDown - Checks whether the user scrolls down. * 5 isScrollExpectedPercent - Detects if the user has scrolled the specified percentage to load more data. * /

const { fromEvent, from } = rxjs;
const { map, filter, pairwise, startWith, exhaustMap } = rxjs.operators

  let currentPage = 1

  const getQuotesAPI = () = > {
   return 'https://node-hnapi.herokuapp.com/news?page=' + currentPage;
  }

  constProcessData =res= > {
    console.log(res)
    res.json().then(news= > {
      currentPage++
      news.forEach(renderNews)
    })
  }
  constRenderNews =(news) = > {
    const li = document.createElement('li')
    li.innerHTML = `${news.id} - ${news.title}`
    scrollElem.appendChild(li)
  }

  const isUserScrollingDown = (position) = > {
    return position[0].sT < position[1].sT
  }

  const isScrollExpectedPercent = (position, percent) = > {
    return ((position.sT + position.cH) / position.sH) > (percent / 100)}// Set the Observable stream
  const scrollElem = document.getElementById('infinite-scroller');
  const scrollEvent$ = fromEvent(scrollElem, 'scroll');
  console.log('scrollEvent$', scrollEvent$);
  // Write the logic for the flow, responsible for handling rolling events and calling the API
  const userScrolledDown$ = scrollEvent$.pipe(
    map(e= > ({
      sH: e.target.scrollHeight,
      sT: e.target.scrollTop,
      cH: e.target.clientHeight
    })),
    pairwise(),
    filter(positions= > {
      return isUserScrollingDown(positions) && isScrollExpectedPercent(positions[1].70)}))const requestOnScroll$ = userScrolledDown$.pipe(
    startWith([]),
    exhaustMap(() = > from(fetch(getQuotesAPI())))
  )

  requestOnScroll$.subscribe(processData)
Copy the code

The appendix

Blog.jerry-hong.com/series/rxjs… rxjs.dev/ cn.rx.js.org/