Skip to content

Instantly share code, notes, and snippets.

@andrewthauer
Created April 28, 2018 15:49
Show Gist options
  • Save andrewthauer/25b5f6bb12e4a2160aa64869cfcc42d2 to your computer and use it in GitHub Desktop.
Save andrewthauer/25b5f6bb12e4a2160aa64869cfcc42d2 to your computer and use it in GitHub Desktop.
RxJS Samples
import * as Rx from 'rxjs';
import { setInterval } from 'timers';
const mockInterval = Rx.Observable.create(obs => {
let i = 0;
setInterval(function() {
i = i + 1;
obs.next(i);
}, 500);
});
const result = mockInterval
.do(o => o) //?
.mergeMap(x =>
x === 13 ?
Rx.Observable.throw('Thirteens are bad') :
Rx.Observable.of('a', 'b', 'c')
)
.catch(() => {
console.log('error caught');
return Rx.Observable.of('catch & toss');
})
;
result.subscribe(
x => console.log(x),
e => console.error(e)
); //?
import * as Rx from 'rxjs';
const delayedWithPromise = value => {
return new Promise(
resolve => setTimeout(() => { resolve(value); }, 5000)
);
};
const delayedWithObservable = value => {
return new Rx.Observable(observer => {
setTimeout(() => { observer.next(value); }, 5000);
});
};
const logMessage = (msg, value = null) => {
const now = new Date(Date.now());
const time = `${now.getHours()}:${now.getSeconds()}`;
const fullMsg = `${time} - ${msg} = ${value}}`;
return console.log(fullMsg);
};
Rx.Observable.of('Delayed by Promise!')
.do(value => logMessage('Starting delayed promise ...'))
.concatMap(value => delayedWithObservable(value))
.subscribe(value => logMessage('Delayed Promise', value));
Rx.Observable.of('Delayed by Observable!')
.do(value => logMessage('Starting delayed observable ...'))
.concatMap(value => delayedWithObservable(value))
.subscribe(value => logMessage('Delayed Observable', value));
import * as Rx from 'rxjs';
const subject = new Rx.Subject();
subject.subscribe(r => {
console.log(r);
});
subject.next('hello');
subject.next('goodbye');
subject.complete()
subject.next('me again');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment