In the application combineLatest is used to combine three observables:
class SomeComponent {
private heightProvider = new SubjectProvider<any>(this);
private marginsProvider = new SubjectProvider<any>(this);
private domainProvider = new SubjectProvider<any>(this);
arbitraryMethod(): void {
combineLatest([
this.heightProvider.value$,
this.marginsProvider.value$,
this.domainProvider.value$
]).pipe(
map(([height, margins, domain]) => {
// ...
}
}
setHeight(height: number): void {
this.heightProvider.next(height);
}
setMargins(margins: {}): void {
this.marginsProvider.next(margins);
}
setDomain(domain: []): void {
this.domainProvider.next(domain);
}
}
However, I've noticed a few times already that I am sometimes forgetting to set one of these observables.
Is there a way I can build in error handeling that throws to console once one of these isn't set?
Observables aren't typically 'set' or 'not set'. I'm not sure what you mean by this. If you have a predicate that can check your observables, here is how you might use it.
// predicate
function notSet(o: Observable<any>): Boolean{
//...
}
scale$: Observable<any> = defer(() => {
const combining = [
this.heightProvider.value$,
this.marginsProvider.value$,
this.domainProvider.value$
];
const allSet = !combining.find(notSet)
if(!allSet) console.log("Not Set Error");
return !allSet?
EMPTY :
combineLatest(combining).pipe(
map(([height, margins, domain]) => {
// ...
}
Update
Ensursing source observables have emitted
If I understand your problem properly, you want to throw an error if any of your source observables haven't emitted yet. At its heart, this feels like a simple problem, but it happens to be a problem for which there doesn't exist a single general solution.
Your solution has to be domain-specific to some extent.
A simplified example of a similar problem
What you're asking a similar to this:
How do I throw an error if 'add' isn't invoked with a second number?
const add = (a: number) => (b: number): number => {
// How do I throw an error if this function
// isn't invoked with a second number?
return a + b;
}
/***********
* Example 1
***********/
// add is being called with one number
const add5 = add(5);
...
/* More code here */
...
// add is being called with a second number
const result = add5(50);
console.log(result); // Prints "55"
/***********
* Example 2
***********/
const result = add(5)(20); // Add is being called with both numbers
console.log(result); // Prints "55"
/***********
* Example 3
***********/
// add is being called with one number
const add5 = add(5);
...
/* More code here */
...
// add was never given a second number
return
// Add throws an error? How?
How can you write add such that it throws an error if the second number isn't 'set'? Well, there's no simple answer. add doesn't know the future and can't guess whether that second number was forgotten or will still be set in the future. To add, those two scenarios look the same.
One solution is to re-write add so that it must take both parameters at once. If either is missing, throw an error:
const add = (a: number, b: number): number => {
if(a != null && b != null){
return a + b;
}
throw "add: invalid argument error";
}
This solution fundamentally changes how add works. This solution doesn't work if I have a requirement that add must take its arguments one at a time.
If I want add to keep that behaviour, perhaps I can set a timer and throw an error if the second argument isn't given fast enough.
const add = (a: number) => {
const t = setTimeout(
() => throw "add: argument timeout error"),
1000 // wait 1 second
);
return (b: number): number => {
clearTimeout(t); // cancel the error
return a + b;
}
}
Now add takes its arguments one at a time, but is a timeout really how I want this to work? Maybe I only care that add is given a second parameter before some other event (an API call returns or a user navigates away from the page) or something.
Hopefully, you can begin to understand how such a "simple" problem has only domain-specific solutions.
Observables
Your question, as writ, doesn't tell us enough about what you're trying to accomplish to guess what behaviour you want.
Observables have a lot of power built into them to allow you to design a solution specific to your needs. It's almost certain that you can throw an error if one of your observables isn't set, but first, you must define what this even means.
Is it not set quickly enough? Is it not set in time for a certain function call? Not set when an event is raised? Never set? How would you like to define never? When the program is shut down?
Maybe you could switch your Subjects for BehaviourSubjects so that they MUST always have a value set (sort of like add taking both arguments at once instead of one at a time).
All of these things (and many many many more) are possible.
Related
Trying to learn RxJs, and I found what looks like a nice tutorial on that topic at https://www.learnrxjs.io.
I'm going through their primer section, and I am not clear on what the return statement in the pipe() function actually does or what it means. These are a couple of screen shots from their tutorial:
In traditional programming, I've always understood a return statement to be an exit - if function A calls function B, and function B has the line return 1, then control goes back to function A.
Is that what happens here? If so, in either of these two examples, where am I returning to???
Or what if I don't want to return anywhere but act on the data immediately? For example, in the error handling example, instead of return makeRequest..., I want to do something like const result = makeRequest.... Can I do that?
In general I'm having some conceptual difficulties around all the returns I've seen used with observables, and any help in explaining what they do/are would be appreciated. So would any other tutorial sites on RxJs.
These are all very similar constructs in javascript
function adder0(a,b){
return a + b
}
const adder1 = (a,b) => {
return a + b
}
const adder2 = (a,b) => a + b
console.log(adder0(3,7)) // 10
console.log(adder1(3,7)) // 10
console.log(adder2(3,7)) // 10
lets re-write the code from that example but with explicit function definitions (instead of arrow syntax).
function maker(value){
return makeRequest(value).pipe(
catchError(handleError)
);
}
function actioner(value){
// take action
}
source.pipe(
mergeMap(maker)
).subscribe(actioner)
The thing to notice is that you never actually call these functions. RxJS does that for you. You give them a function and they'll call it when they're good and ready based on the spec for a given operator.
How is it possible with RXJS to make a cascaded forEach loop? Currently, I have 4 observables containing simple string lists, called x1 - x4. What I want to achieve now is to run over all variation and to call a REST-Api with an object of variation data. Usually, I would do something like that with a forEach, but how to do with RXJS? Please see the abstracted code:
let x1$ = of([1,2]);
let x2$ = of([a,b,c,d,e,f]);
let x3$ = of([A,B,C,D,E,F]);
let x4$ = of([M,N,O,P]);
x1$.forEach(x1 => {
x2$.forEach(x2 => {
x3$.forEach(x3 => {
x4$.forEach(x4 => {
let data = {
a: x1,
b: x2,
c: x3,
d: x4
}
return this.restService.post('/xxxx', data)
})
})
})
})
Is something like that possible with RXJS in an elegant way?
Let's assume you have a function combineLists which represent the plain-array version of the logic to turn static lists into an array of request observables:
function combineLists(lists: unknown[][]) {
const [x1s, x2s, x3s, x4s] = lists;
// Calculate combinations, you can also use your forEach instead
const combinations = x1s
.flatMap(a => x2s
.flatMap(b => x3s
.flatMap(c => x4s
.flatMap(d => ({a, b, c, d})))));
return combinations.map(combination => this.restService.post('/xxxx', combination));
}
Since your input observables are one-offs as well, we can use e.g. forkJoin. This waits for all of them to complete and then runs with their respective plain values. At this point you're back to computing the combinations with your preferred method.
forkJoin([x1$, x2$, x3$, x4$]).pipe(
map(combineLists),
);
Assuming your REST call is typed to return T, the above produces Observable<Observable<T>[]>. How you proceed from here depends on what data structure you're looking for / how you want to continue working with this. This didn't seem to be part of your question anymore, but I'll give a couple hints nonetheless:
If you want a Observable<T>, you can just add e.g. a mergeAll() operator. This observable will just emit the results of all individual requests after another in whichever order they arrive.
forkJoin([x1$, x2$, x3$, x4$]).pipe(
map(combineLists),
mergeAll(),
);
If you want an Observable<T[]> instead, which collects the results into a single emission, you could once again forkJoin the produced array of requests. This also preserves the order.
forkJoin([x1$, x2$, x3$, x4$]).pipe(
map(combineLists),
switchMap(forkJoin),
);
Some words of caution:
Don't forget to subscribe to make it actually do something.
You should make sure to handle errors on all your REST calls. This must happen right at the call itself, not after this entire pipeline, unless you want one single failed request to break the entire pipe.
Keep in mind that forkJoin([]) over an empty array doesn't emit anything.
Triggering a lot of requests like this probably means the API should be changed (if possible) as the number of requests grows exponentially.
I am trying to understand why share RxJs operator works differently if the source Observable is created with range instead of timer.
Changing the original code to:
const source = range(1, 1)
.pipe(
share()
)
const example = source.pipe(
tap(() => console.log('***SIDE EFFECT***')),
mapTo('***RESULT***'),
)
const sharedExample = example
const subscribeThree = sharedExample.subscribe(val => console.log(val))
const subscribeFour = sharedExample.subscribe(val => console.log(val))
Results in:
console.log src/pipeline/foo.spec.ts:223
SIDE EFFECT
console.log src/pipeline/foo.spec.ts:228
RESULT
console.log src/pipeline/foo.spec.ts:223
SIDE EFFECT
console.log src/pipeline/foo.spec.ts:229
RESULT
Basically, the side effect is invoked more than once.
As far as I know range is supposed to be a cold observable but it is said that share should turn cold observables to hot.
What is the explanation behind this behaviour ?
Two things to point out.
First, if you look closely at the function signature for range, you'll see it takes a third parameter, a SchedulerLike.
If unspecified, RxJS calls the next handler of each subscriber immediately with the relevant value for the range observable until it's exhausted. This isn't desirable if you intend to use the share operator, because it effectively bypasses any shared side effect processing that might be introduced.
Relevant snippet taken from the actual implementation:
// src/internal/observable/range.ts#L53
do {
if (index++ >= count) {
subscriber.complete();
break;
}
subscriber.next(current++);
if (subscriber.closed) {
break;
}
} while (true);
timer also takes an optional SchedulerLike argument. If unspecified, the implementation adopts AsyncScheduler by default, different to the default for range.
Secondly, the share operator should follow all other operators that might have side effects. If it precedes them, the expected unifying behaviour of pipe operator processing is lost.
So, with both points in mind, to make the share operator work with range as you're expecting:
const { asyncScheduler, range, timer } = rxjs;
const { mapTo, tap, share } = rxjs.operators;
// Pass in an `AsyncScheduler` to prevent immediate `next` handler calls
const source = range(1, 1, asyncScheduler).pipe(
tap(() => console.log('***SIDE EFFECT***')),
mapTo('***RESULT***'),
// All preceding operators will be in shared processing
share(),
);
const sub3 = source.subscribe(console.log);
const sub4 = source.subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
I would expect the following two pieces of code to be equivalent. Repeat uses a currentThread scheduler by default. If we change it ti an immediate scheduler:
Rx.Observable.fromArray([1,2,3,4,5]).flatMap(a => {
return Rx.Observable.repeat(a, 3, Rx.Scheduler.immediate)
})
.subscribe(r => console.log(r));
The code above produces the expected result: 1, 1, 1, 2, 2, 2, .... But the following code doesn't, and produces a sequence of mixed values:
Rx.Observable.fromArray([1,2,3,4,5]).flatMap(a => {
return Rx.Observable.repeat(a, 3).observeOn(Rx.Scheduler.immediate)
})
.subscribe(r => console.log(r));
I don't understand this behavior, but I guess I am missing something. repeat can be passed a Scheduler parameter, but I thought I could also force the Observable on a particular Scheduler by using observeOn. What am I missing?
The difference is that one is using the scheduler for generation, the second is just using it for propagation.
In the second version you are still using currentThread for the creation of the values. observeOn will only coerce values onto different schedulers after they are emitted from the previous operator but for operators that generate events this won't affect the generation of those events.
If you look inside of some of the creation operators (like fromArray) you'll see something like:
//Changing the scheduler will change how recursive scheduling works
scheduler.schedulerRecursiveWithState(0, function(self, state) {
if (i < len) {
observer.onNext(array[i]);
//Schedule the next event
self(i + 1);
} else {
observer.onCompleted();
}
});
whereas observeOn is akin to doing something like:
//Doesn't change when events get generated, simply reschedules them for down stream
source.subscribe(function(x) {
scheduler.scheduleWithState(x, function(self, state) {
observer.onNext(x);
});
});
I am wondering if there's a way to create a promise chain that I can build based on a series of if statements and somehow trigger it at the end. For example:
// Get response from some call
callback = (response) {
var chain = Q(response.userData)
if (!response.connected) {
chain = chain.then(connectUser)
}
if (!response.exists) {
chain = chain.then(addUser)
}
// etc...
// Finally somehow trigger the chain
chain.trigger().then(successCallback, failCallback)
}
A promise represents an operation that has already started. You can't trigger() a promise chain, since the promise chain is already running.
While you can get around this by creating a deferred and then queuing around it and eventually resolving it later - this is not optimal. If you drop the .trigger from the last line though, I suspect your task will work as expected - the only difference is that it will queue the operations and start them rather than wait:
var q = Q();
if(false){
q = q.then(function(el){ return Q.delay(1000,"Hello");
} else {
q = q.then(function(el){ return Q.delay(1000,"Hi");
}
q.then(function(res){
console.log(res); // logs "Hi"
});
The key points here are:
A promise represents an already started operation.
You can append .then handlers to a promise even after it resolved and it will still execute predictably.
Good luck, and happy coding
As Benjamin says ...
... but you might also like to consider something slightly different. Try turning the code inside-out; build the then chain unconditionally and perform the tests inside the .then() callbacks.
function foo(response) {
return = Q().then(function() {
return (response.connected) ? null : connectUser(response.userData);
}).then(function() {
return (response.exists) ? null : addUser(response.userData);//assuming addUser() accepts response.userData
});
}
I think you will get away with returning nulls - if null doesn't work, then try Q() (in two places).
If my assumption about what is passed to addUser() is correct, then you don't need to worry about passing data down the chain - response remains available in the closure formed by the outer function. If this assumption is incorrect, then no worries - simply arrange for connectUser to return whatever is necessary and pick it up in the second .then.
I would regard this approach to be more elegant than conditional chain building, even though it is less efficient. That said, you are unlikely ever to notice the difference.