Giter Club home page Giter Club logo

learn-rxjs's Introduction

Introduction

Clear examples, explanations, and resources for RxJS.

By @btroncone

Introduction

RxJS is one of the hottest libraries in web development today. Offering a powerful, functional approach for dealing with events and with integration points into a growing number of frameworks, libraries, and utilities, the case for learning Rx has never been more appealing. Couple this with the ability to utilize your knowledge across nearly any language, having a solid grasp on reactive programming and what it can offer seems like a no-brainer.

But...

Learning RxJS and reactive programming is hard. There's the multitude of concepts, large API surface, and fundamental shift in mindset from an imperative to declarative style. This site focuses on making these concepts approachable, the examples clear and easy to explore, and features references throughout to the best RxJS related material on the web. The goal is to supplement the official docs and pre-existing learning material while offering a new, fresh perspective to clear any hurdles and tackle the pain points. Learning Rx may be difficult but it is certainly worth the effort!

Ultimate RxJS

Brand New to RxJS?

Start getting familiar with all the key concepts needed to be productive with our RxJS Primer!

Content

Operators

Operators are the horse-power behind observables, providing an elegant, declarative solution to complex asynchronous tasks. This section contains all RxJS operators, included with clear, executable examples. Links to additional resources and recipes for each operator are also provided, when applicable.

Operator Categories

OR...

Complete listing in alphabetical order

Understanding Subjects

A Subject is a special type of Observable which shares a single execution path among observers.

Concepts

Without a solid base knowledge of how Observables work behind the scenes, it's easy for much of RxJS to feel like 'magic'. This section helps solidify the major concepts needed to feel comfortable with reactive programming and Observables.

Recipes

Recipes for common use-cases and interesting solutions with RxJS.

Introductory Resources

New to RxJS and reactive programming? In addition to the content found on this site, these excellent resources will help jump start your learning experience!

Conferences

Reading

Videos

Exercises

Tools

Interested in RxJS 4? Check out Denis Stoyanov's excellent eBook!

Translations

A Note On References

All references included in this GitBook are resources, both free and paid, that helped me tremendously while learning RxJS. If you come across an article or video that you think should be included, please use the edit this page link in the top menu and submit a pull request. Your feedback is appreciated!

learn-rxjs's People

Contributors

adamlubek avatar ajrussellaudio avatar alex0007 avatar anddam avatar artemloiko avatar arturoromeroslc avatar atellmer avatar ayeletdn avatar barryrowe avatar bernabe-felix avatar bernabefelix avatar bfaulk96 avatar btiwaree avatar btroncone avatar cmckni3 avatar elshahat avatar enstain avatar julienrouse avatar larrybattle avatar markgoodyear avatar mlrv avatar mobiletainment avatar rtpharry avatar sampath-karupakula avatar sangka avatar serkansipahi avatar stpnvntn avatar thewarpaint avatar voloshchenkoal avatar yuhle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

learn-rxjs's Issues

(suggestion) usage pluck for arrays

pluck can be used after combineLatest/withLatestFrom as well

map(([unusedValue, usedValue]) => usedValue)
can be replaced by
pluck(1)

It's not documented. Can be?

Content summary on primer ?

I think it'd be useful to have contents summary with navigable links on top of primer, what do you think?

Tabnapping vulnerability

The »Additional Resources« (and possibly other) links currently use target="_blank", which opens a security vulnerability as the opened page is external and gets a reference via window.opener. All links opening in new windows should add rel="noopener".

Given that the links are not directly user content the issue is relatively minor at the moment, but should still be fixed.

See https://mathiasbynens.github.io/rel-noopener/ for an in-depth discussion of the issue.

Adding Documentation for `ajax` operator

Love what you are doing here 🥇 Documentation really helped me when I started with Rxjs and still does 👍

I have the feeling, and please correct me if I am wrong, that ajax operator is missing.
Can be found here.

I am happy to help you add it. Please let me know if you need any help or if there is a reason that this is not added that I didnt know.

partition example on stackblitz shows typing error

When looking at the example I am getting a typing error:

(Argument of type 'UnaryFunction<Observable<number>, [Observable<number>, Observable<number>]>' is not assignable to parameter of type 'OperatorFunction<any, any>'.)

I got the same message when I tried to use partition in NGRX Effects.

GroupBy example

The example of groupBy uses .flatMap(group => group.reduce((acc, curr) => [...acc, curr], [])). Is it not better to use .flatMap(group => group.toArray())? Or does it have a performance impact? This is the full code:

const Rx = require("rxjs");

const people = [{ name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: 'Frank', age: 25 }, { name: 'Sarah', age: 35 }];
//emit each person
const source = Rx.Observable.from(people);
//group by age
const example = source
    .groupBy(person => person.age)
    //return as array of each group
    .flatMap(group => group.toArray())
    // .flatMap(group => group.reduce((acc, curr) => [...acc, curr], []))
    /*
      output:
      [{age: 25, name: "Sue"},{age: 25, name: "Frank"}]
      [{age: 30, name: "Joe"}]
      [{age: 35, name: "Sarah"}]
    */
const subscribe = example.subscribe(console.log);

Thank you!

Update examples of some operators based on the changes for v6

Firstly, I must say this GitBook is really helpful. Great work!

And I think it would be better to update some examples based on the changes for v6 such as import path and deleting result selectors.

I'd love to contribute this but wondering if it's okay to send PR after changing some piece, not the whole operators.

Thank you!

throttleTime wrong explanation

It says throttleTime emits the latest value (as if leading: false, trailing: true was used) but throttleTime's default behaviour is to emit the first value.
The example output of example 1 is wrong also.

From https://www.learnrxjs.io/operators/filtering/throttletime.html

Emit latest value when specified duration has passed.

Example 1
last value emitted before throttle ends will be emitted from source

From https://rxjs-dev.firebaseapp.com/api/operators/throttleTime

Emits a value from the source Observable, then ignores subsequent source values for duration milliseconds, then repeats this process.

Lets a value pass, then ignores source values for the next duration milliseconds.

(suggestion) show/explain BehaviorSubject.value usage

a BehaviorSubjects value can be accessed by the value property or by subscribing.

// RxJS v6+
import { BehaviorSubject } from 'rxjs';

const subject = new BehaviorSubject(123);

// new subscribers will get initial value => output: 123
subject.subscribe(console.log);

subject.next(345)

// current value can also be accessed by using the value property
console.log(subject.value)

// output: 345

[Question] combineLatest

https://github.com/btroncone/learn-rxjs/blob/master/operators/combination/combinelatest.md

import { Observable } from 'rxjs/Observable';

import { timer } from 'rxjs/observable/timer';
import { combineLatest } from 'rxjs/observable/combineLatest';

const timerOne$ = Observable::timer(1000, 4000);
const timerTwo$ = Observable::timer(2000, 4000);
const timerThree$ = Observable::timer(3000, 4000);

Observable::combineLatest(
    timerOne$, timerTwo$, timerThree$,
    (one, two, three) => `${one}, ${two}, ${three}`
  )
  .subscribe((latestValuesProject) => console.log(latestValuesProject));
  // 0, 0, 0
  // 1, 0, 0
  // 1, 1, 0
  // 1, 1, 1
  // 2, 1, 1
  // 2, 2, 1
  // 2, 2, 2
  // ...

Let operator issues

In the Example 1 of the let operator, the output of jsBin online example was incorrect:

The output should be : 4,5,6,7,8

//emit array as a sequence
const source = Rx.Observable.from([1,2,3,4,5]);
//demonstrating the difference between let and other operators
const test = source
  .map(val => val + 1)
  /*
  	this would fail, let behaves differently than most operators
  	val in this case is an observable
  */
//   .let(val => val + 2)
  .subscribe(val => console.log('VALUE FROM ARRAY: ', val));

const subscribe = source
  .map(val => val + 1)
  //'let' me have the entire observable
  .let(obs => obs.map(val => val + 2))
  //output: 2,3,4,5,6
  .subscribe(val => console.log('VALUE FROM ARRAY WITH let: ', val));

Request: Recepie for shared resource updates

Thank you for the examples, they really help. The only thing that really left me puzzled was how to create a source for the events that don't leak memory. The examples that rely on the timer are great for explaining what should happen after the event, it would rock to have one that delves into how to build the event generation.

Below is the example that I'm trying to find.

Service 1 has a resource that has multiple subscribers.
Subsciber A subscribes to resource
Service 1 has the resource set to initial value (A)
Subscriber B subscribes to resource
Service 1 updates the resource (B)

expected output
subsciber A (AB)
subscriber B (AB)

The service 1 interface would have the following api
The resource
A method to add a new updated resource.

pluck example #2 links

Hi,

For pluck example#2, the jsbin and jsfiddle examples are going to link with code from example#1

example#1 jsbin link: http://jsbin.com/zokaxiwahe/1/edit?js,console
example#2 jsbin link: http://jsbin.com/joqesidugu/1/edit?js,console

example#1 jsfiddle link: https://jsfiddle.net/btroncone/58v9xq0f/
example#1 jsfiddle link: https://jsfiddle.net/btroncone/n592m597/

example#2 stackblitz, it is going to the right link but there's error

Would love to fix it but don't know where to start :)

Thanks,
Alex

`do` operator example does not use `do`

In https://github.com/btroncone/learn-rxjs/blob/master/operators/utility/do.md, here is the example code:

import { of } from 'rxjs/observable/of';
import { tap, map } from 'rxjs/operators';

const source = of(1, 2, 3, 4, 5);
//transparently log values from source with 'do'
const example = source.pipe(
  tap(val => console.log(`BEFORE MAP: ${val}`)),
  map(val => val + 10),
  tap(val => console.log(`AFTER MAP: ${val}`))
)
  
//'do' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));

do is referenced in the comments, but not the code.

Rx.Observable.merge seems to return an array not a new observable

Not sure if this is a doc bug or library bug but

Rx.Observable.merge seems to return an array not a new observable

but the docs say:

signature: merge(input: Observable): Observable

Turn multiple observables into a single observable.
Rx.Observable.timer(1)

here is my proof:

screenshot from 2017-01-09 20-32-26

lastly I want to say thank you for these docs, hopefully I am right about this bug, and in that case very willing to tolerate a little bit of wonkiness for a bit, thanks

Add links to RxViz for code samples?

I recently found RxViz (https://rxviz.com/) which is a very intuitive animated view of RxJS streams. I was just thinking it would be very cool to extend the code links you have for the examples to include the ability to show the example in RxViz. I have no idea if that's possible, but if it is, it seems like it could be very useful to help folks visualize what's happening.

(suggestion) Illustrations in docs

I find these docs a great resource and a good point of reference when working with rxjs, and I find them almost always sufficient to keep me on the right path without having to refer to the official docs.

However one thing which I feel is missing which I find to be exceptionally useful when referencing operators, is the illustrations which demonstrate the nature of the emission according to the operator. Taking merge as an example, when paired with the image from the official docs:
merge
For those who learn better with visual cues, this could be invaluable...

I'm unsure how this would need to be considered in terms of licensing etc?

tetris game impure function

I love how you wanted to code tetris game with rxjs but I think it could be more elegant
handleKeyPress and rotate and collide and score they all mutate state but it was better that it return a new state

Observable.catch() a bit misleading

Thanks for creating this great resource! While learning I found a small issue with the catch operator's description.

TL;DR: Gracefully handle errors and exceptions **without terminating** observable

The catch operator allows us to capture errors and exceptions, returning an observable.
Properly caught errors **will avoid terminating** a subscription chain.

It suggests the subscription will stay working after the error is thrown in the Observable, but it's not what will really happen. The error will terminate the original Observable anyway. The effect of using the catch operator is that it will trigger the onNext callback, rather than onError before executing the onFinish and ending the subscription.

http://jsbin.com/diwaheyawu/edit?js,console

need example to make more clear bufferWithTimeOrCount

spec of bufferWithTimeOrCount: http://reactivex.io/documentation/operators/buffer.html
implementation: ReactiveX/rxjs#1556
need an example in order to make more clear the behavior in https://www.learnrxjs.io/operators/transformation/buffertime.html
+
need change signature for bufferTime from

bufferTime(bufferTimeSpan: number, bufferCreationInterval: number, scheduler: Scheduler): Observable

in accordance with
https://github.com/ReactiveX/rxjs/blob/441d52208df8b9247b01f8ca3993e3a7b0870b10/src/internal/operators/bufferTime.ts#L12

Incorrect example combineAll

//emit every 1s, take 2
const source = Rx.Observable.interval(1000).take(2);
//map first value to 500ms interval **and second to 1s,** take two values
const example = source.map(val => Rx.Observable.interval(val + 500).take(2));

The first source value is mapped to interval of 0 + 500 (half second) and the second to 1 + 500 (that's not one second). Also you could choose 25 instead of 500 in the original example: the output is the same. You could choose 2000 instead of 500: the output is the same. The example should focus on combineAll, clear of misleading comments.

site doesn't work on Safari

I'd say 60% of the time I'm browsing the docs the right side (main content) of the screen is white. I can get it to come back if I resize the window.

[Question] create

https://github.com/btroncone/learn-rxjs/blob/master/operators/creation/create.md

import { Observable } from 'rxjs/Observable';

// I use these two can not be executed.
import { create } from 'rxjs/observable/create';  // Error: Cannot find module 'rxjs/observable/create'
import { create } from 'rxjs/operator/create';  // Error: Cannot find module 'rxjs/operator/create'

Observable::create(observer => {
    observer.next('Hello');
    observer.next('World');
  })
  .subscribe(result => console.log(result));

or

import { Observable } from 'rxjs/Observable';

// I use these two can not be executed.
import 'rxjs/observable/create';  // Error: Cannot find module 'rxjs/observable/create'
import 'rxjs/operator/create';  // Error: Cannot find module 'rxjs/operator/create'

Observable.create(observer => {
    observer.next('Hello');
    observer.next('World');
  })
  .subscribe(result => console.log(result));

OK

import * as Rx from 'rxjs';

Rx.Observable.create(observer => {
    observer.next('Hello');
    observer.next('World');
  })
  .subscribe(result => console.log(result));
  // Hello
  // World

Webworker example?

It would be splendid to have an example where UI components subscribe to Observables being fed from data produced in a web worker.

Love your work!

Switchmap: Example 4: Countdown timer with switchMap could be clearer

Hi,

It takes a while to understand "Example 4: Countdown timer with switchMap" on
https://www.learnrxjs.io/operators/transformation/switchmap.html

Mostly, my confusion is due to startsWith(interval$).

Original code:

const timer$ = merge(pause$, resume$)
  .pipe(
    startWith(interval$),
    switchMap(val => (val ? interval$ : empty())),
    scan((acc, curr) => (curr ? curr + acc : acc), countdownSeconds),
    takeWhile(v => v >= 0)
  )
  .subscribe(setHTML('remaining'));

I think it is better to have startsWith(true) there because we want to start the timer right away. And, I am not sure what is the effects of having startsWith(interval$), because testing on jsfiddle shows that the code has no effects.

Newly purposed code:

const timer$ = merge(pause$, resume$)
  .pipe(
    startWith(true),
    switchMap(val => (val ? interval$ : empty())),
    scan((acc, curr) => (curr ? curr + acc : acc), countdownSeconds),
    takeWhile(v => v >= 0)
  )
  .subscribe(setHTML('remaining'));

Simple easing in smart counter example

I'm trying to understand how I can apply some simple easing function to the smart counter example but all I could achieve is that only the first execution was delayed.

For example I did something like that:

.delayWhen((i) => {
  return Rx.Observable.interval(i + 1000);
 })

text-shadow

Please, throw out the text-shadow of code samples. Our eyes are bleeding because of it...
This property had gone there from prism.css

catch-spec: error variable

Usually we can do something like this inside our Observables, throw an error with a message. As in RxJS docs.

observer.error('Not authorized to record audio');

Is it possible to specify here, when testing, what is the message of the error too?
Maybe attributing a variable to it, as we do with usual values emitted.

If so, it would be great to have an example for this also.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.