const promise = new Promise((resolve, reject) => {
... long running code
resolve(data);
});
const obs$ = new Observable(observer => {
... long running code
observer.next(data);
observer.next(data);
observer.complete();
});
let obs$ = new Observable(() =>
console.log('work');
);
obs$.subscribe()
obs$.toPromise()
new Promise(() =>
console.log('work');
);
const promise = new Promise((resolve, reject) => {
... long running code
reject('It went wrong');
});
const obs$ = new Observable(observer => {
... long running code
observer.error('It went wrong');
});
obs$.subscribe(onTick, onError, onComplete);
function interval(time) {
return new Observable(observer => {
let counter = 1;
setInterval(() =>
observer.next(counter++);
}, time);
});
}
const subscription = interval$.subscribe(onTick);
subscription.unsubscribe();
const subscription = createInterval$(1000)
.subscribe(val => console.log(val));
subscription.unsubscribe();
function createInterval$(time) {
return new Observable(observer => {
let counter = 1;
setInterval(() => {
console.log('XXX');
observer.next(counter++);
}, time);
});
}
const subscription = createInterval$(1000)
.subscribe(val => console.log(val));
subscription.unsubscribe();
function createInterval$(time) {
return new Observable(observer => {
let counter = 1;
const interval = setInterval(() => {
console.log('XXX');
observer.next(counter++);
}, time);
return () => clearInterval(interval);
});
}
let subscription = interval$.subscribe(onTick);
subscription = interval$.subscribe(onTick);
subscription.unsubscribe();
const obs$ = from([1,2,3,4]);
console.log('one');
obs$.subscribe(
x => console.log(x),
null,
() => console.log('done')
);
console.log('two');
const derived$ = interval(1000).pipe(
map(x => x * 2)
);
derived$.subscribe(x => console.log(x));
const interval$ = interval(1000);
const derived$ = interval$.pipe(
map(x => x * 2)
);
interval$.subscribe(x => console.log(x));
[1,2,3,4,5].reduce((acc, curr) =>
acc + curr
);
Arrays
from([1,2,3,4,5]).pipe(reduce((acc, curr) =>
acc + curr
));
Observables
from([1,2,3,4,5]).pipe(scan((acc, curr) =>
acc + curr
, 0));
function isPrime(n) {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return n !== 1 && n !== 0;
}
const intervalOne$ = interval(1000);
const intervalTwo$ = interval(500);
merge(intervalOne$, intervalTwo$).subscribe(...)
const intervalOne$ = timer(1000, 1000);
const intervalTwo$ = timer(5000, 500);
combineLatest(intervalOne$, intervalTwo$).subscribe(...)
// 4, 0 <- depends on the first one to emit
// 5, 0
// 5, 1
// 5, 2
// 6, 3
// 6, 4
const intervalOne$ = timer(1000, 1000).pipe(take(3));
const intervalTwo$ = timer(5000, 500).pipe(take(5));
forkJoin(intervalOne$, intervalTwo$).subscribe(...)
// 2, 4
interval(5000).pipe(
switchMap(() => interval(500))
)
GET https://api.chucknorris.io/jokes/random
const subject = new Subject();
subject.subscribe(x => console.log(x));
subject.next(1);
subject.next(2);
<button (click)="methodInClass()">
click me
</button>