Learn RxJS
Search…
let

signature: let(function): Observable

Let me have the whole observable.

let is no longer available, or necessary, with pipeable operators! (RxJS 5.5+)

Examples

Example 1: Reusing error handling logic with let
1
// custom error handling logic
2
const retryThreeTimes = obs =>
3
obs.retry(3).catch(_ => Rx.Observable.of('ERROR!'));
4
const examplePromise = val =>
5
new Promise(resolve => resolve(`Complete: ${val}`));
6
7
//faking request
8
const subscribe = Rx.Observable.of('some_url')
9
.mergeMap(url => examplePromise(url))
10
// could reuse error handling logic in multiple places with let
11
.let(retryThreeTimes)
12
//output: Complete: some_url
13
.subscribe(result => console.log(result));
14
15
const customizableRetry = retryTimes => obs =>
16
obs.retry(retryTimes).catch(_ => Rx.Observable.of('ERROR!'));
17
18
//faking request
19
const secondSubscribe = Rx.Observable.of('some_url')
20
.mergeMap(url => examplePromise(url))
21
// could reuse error handling logic in multiple places with let
22
.let(customizableRetry(3))
23
//output: Complete: some_url
24
.subscribe(result => console.log(result));
Copied!
Example 2: Applying map with let
1
//emit array as a sequence
2
const source = Rx.Observable.from([1, 2, 3, 4, 5]);
3
//demonstrating the difference between let and other operators
4
const test = source
5
.map(val => val + 1)
6
/*
7
this would fail, let behaves differently than most operators
8
val in this case is an observable
9
*/
10
//.let(val => val + 2)
11
.subscribe(val => console.log('VALUE FROM ARRAY: ', val));
12
13
const subscribe = source
14
.map(val => val + 1)
15
//'let' me have the entire observable
16
.let(obs => obs.map(val => val + 2))
17
//output: 4,5,6,7,8
18
.subscribe(val => console.log('VALUE FROM ARRAY WITH let: ', val));
Copied!
Example 3: Applying multiple operators with let
1
//emit array as a sequence
2
const source = Rx.Observable.from([1, 2, 3, 4, 5]);
3
4
//let provides flexibility to add multiple operators to source observable then return
5
const subscribeTwo = source
6
.map(val => val + 1)
7
.let(obs =>
8
obs
9
.map(val => val + 2)
10
//also, just return evens
11
.filter(val => val % 2 === 0)
12
)
13
//output: 4,6,8
14
.subscribe(val => console.log('let WITH MULTIPLE OPERATORS: ', val));
Copied!
Example 4: Applying operators through function
1
//emit array as a sequence
2
const source = Rx.Observable.from([1, 2, 3, 4, 5]);
3
4
//pass in your own function to add operators to observable
5
const obsArrayPlusYourOperators = yourAppliedOperators => {
6
return source.map(val => val + 1).let(yourAppliedOperators);
7
};
8
const addTenThenTwenty = obs => obs.map(val => val + 10).map(val => val + 20);
9
const subscribe = obsArrayPlusYourOperators(addTenThenTwenty)
10
//output: 32, 33, 34, 35, 36
11
.subscribe(val => console.log('let FROM FUNCTION:', val));
Copied!

Additional Resources

    let
    📰 - Official docs
Last modified 1yr ago