How to use LOGICAL OR Operator on Observable Boolean in Angular/RxJS - rxjs

I am trying to do the logical OR/AND operator on two observable Boolean values.
I looked around a little and found on some old questions that combineLatest could be used for that, but it seems unfortunately it is deprecated now, and I can't find any other way to accomplish the same task.
Just things which might or might not make what I seek easier.
I need a way to apply OR operator on them in such a way that the resulting variable is also an observable Boolean and not just a Boolean (although this might work for me too).
Let me know what function or reference I can use to accomplish my task.

combineLatest ain't deprecated, at least not the form taking an array as argument :
import { combineLatest, of, map } from 'rxjs'
combineLatest(
[
of(true),
of(false)
]
)
.pipe(
map(([bool1, bool2]) => bool1 || bool2)
)
.subscribe(console.log)

Related

Is it bad to use a variable from outside the observable pipe within an operator?

Is using a variable from outside an observable within an operator considered a (significantly) bad practice?
createObservableExample1(parameter1: string, obs$: Observable<string>): Observable<string> {
return obs$.pipe(
map( x => {
const returnValue = `${parameter1}, ${x}`;
return returnValue;
})
);
}
I understand you can do something like this:
createObservableExample2(parameter1: string, obs$: Observable<string>): Observable<string> {
return combineLatest([
of(parameter1),
obs$
]).pipe(
map( (x, y) => {
const returnValue = `${x}, ${y}`;
return returnValue;
})
);
}
But is it worth it?
Does this just come down to accessing variables from outside the scope of anonymous function? Would this force the context of the enclosing method to exist for longer than it should? I remember a code tool I used to use for C# complaining about something similar to this. I have found somewhat related topics by searching for, "anonymous functions and closures", but as of yet, nothing really discussing the scenario explained above.
I ask because I have been creating some relatively complex observables that have enormous operator chains, and constantly adding the needed variables, using combineLatest and of, from the parent scope can make the code even harder to follow.
When I teach Reactive programming to neophytes, I try to make them grasp : Do not break the reactivity by having uneccessary side effects :
no input that from a state (for example using a class or instance property
no storing outside value.
There is none of these red flags in your example. Your function is pure & idempotent with both implementation, go with what ever you like and if possible be consistant within your code base !

RXJS Observables how to access multiple observable values from mergeMap

I have an rxjs function using several rxjs operators from which I need to ultimately return an observable. My challenge is detailed below in the sample code with details of what I am trying to do. How can I accomplish this? Do I need a rewrite? Without the change I'm trying to make to access the values from Observable3 everything works as needed. I've tried many things including using withLatestFrom to bring in observable three and also combineLatest but to no luck.
Observable3 = of({obs3Prop1: value1, obs3Prop2: value2})
this.Observable1
        .pipe(
            switchMap(param1) => {
                return this.getCount(param1);
            }), 
            mergeMap((param2: number) => 
                this.Observable2
                .pipe(
//inside this pipe, return another observable from here using some rxjs operators
//where I need access to param2
//but I also need access to the value from Observable3
                )
            ),
        )
It seems like you could use just forkJoin() assuming the all source Observables complete:
mergeMap((param2: number) =>
forkJoin([
Observable3,
this.Observable2,
]).pipe(
mergeMap(([o3params, o2params]) => this.makeCall(o3params.param1, o2params)),
)
),

Should an rxjs operator return a function or an observable?

I'm a bit confused by the various definitions of an operator in rxjs.
Below I provide some of the definitions:
1 A Pipeable Operator is a function that takes an Observable as its input and returns another Observable.
Creation Operators are the other kind of operator, which can be called as standalone functions to create a new Observable
2 An operator is a function that takes one observable (the source) as its first argument and returns another observable (the destination, or outer observable)
3 Operators take configuration options, and they return a function that takes a source observable.
4 Operators should always return an Observable [..] If you create a method that returns something other than an Observable, it's not an operator, and that's fine.
Since 1,2,4 seem to be conflicting with 3, which definition is the correct one. Is there a better definition of rxjs operators?
For example: in case of map. Is map() itself the operator? Or the operator is the return value of map()?
Is map() itself the operator? Or the operator is the return value of map()?
Current implementation of the map() looks like this:
export function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {
return function mapOperation(source: Observable<T>): Observable<R> {
if (typeof project !== 'function') {
throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
}
return source.lift(new MapOperator(project, thisArg));
};
}
So, map() is a function. It is an operator in RxJS terms, yes, but it's still a regular JavaScript function. That's it.
This operator receives projection callback function which gets called by the map operator. This callback is something you're passing to map(), e.g. value => value.id from this example:
source$.pipe(map(value => value.id))
The return value of the map is also a function (declared as OperatorFunction<T, R>). You can tell that it is a function since map returns function mapOperation().
Now, mapOperation function receives only one parameter: source which is of type Observable<T> and returns another (transformed) Observable<R>.
To summarize, when you say:
A Pipeable Operator is a function that takes an Observable as its input and returns another Observable.
This means that an RxJS operator (which is a function) is pipeable when it takes an Observable as its input and returns another Observable which in our case is true: a map operator indeed returns a function (mapOperation) whose signature ((source: Observable<T>): Observable<R>) indicates exactly that: it takes one Observable and returns another.
An operator is a function that takes one observable (the source) as its first argument and returns another observable (the destination, or outer observable)
I already mentioned couple of times that an operator is a just function.
Operators take configuration options, and they return a function that takes a source observable.
Yes, in this case, a map() could be called operator since it receives configuration option - a projecttion callback function. So, there's really no conflicts here since many operators are configurable.
I'd say that there's conflict in this one:
Operators should always return an Observable [..] If you create a method that returns something other than an Observable, it's not an operator, and that's fine.
I guess that this is an old definition when pipeable operators weren't pipeable. Before pipeable operators were introduced (I think in version 5 of RxJS), operators were returning Observables. An old map() implementation indicates just that.
For more information about why creators of RxJS decided to introduce pipeable operators, please take a look at this document.
Another great article about what are Observables can be found here.
Also:
Creation Operators are the other kind of operator, which can be called as standalone functions to create a new Observable.
of() is an example of creation operator which returns (creates) an Observable. Please take a look at the source code.
TL;DR: A map() is a function that usually has one parameter (a projection callback function) which also returns a function that receives a source Observable and returns a destination Observable.
EDIT: To answer your question from comments, I'd like to do it here.
Yes, in RxJS 6 you can create a function that accepts observable and returns another one and that would be the operator. E.g.
function myOperatorFunction(s: Observable<any>) {
return of(typeof s);
}
and you'd call it like
source$.pipe(myOperatorFunction);
Please notice that I didn't call myOperatorFunction in pipe(), I just passed the reference to it, i.e. I didn't write myOperatorFunction with parenthesis, but without them. That is because pipe receives functions.
In cases where you need to pass some data or callback functions, like in map example, you'd have to have another function that would receive your parameters, just like map receives projection parameter, and use it however you like.
Now, you may wonder why there are operators that don't receive any data, but are still created as functions that return function, like refCount(). That is to coincide with other operators that mostly have some parameters so you don't have to remember which ones don't receive parameters or which ones have default parameters (like min()). In case of refCount, if it was written a bit different than it is now, you could write
source$.pipe(refCountOperatorFunction);
instead of
source$.pipe(refCount());
but you'd have to know that you have to write it this way, so that is the reason why functions are used to return functions (that receives observable and returns another observable).
EDIT 2: Now that you know that built in operators return functions, you could call them by passing in source observable. E.g.
map(value => value.toString())(of())
But this is ugly and not recommended way of piping operators, though it would still work. Let's see it in action:
of(1, 2, true, false, {a: 'b'})
.pipe(
map(value => value.toString()),
filter(value => value.endsWith('e'))
).subscribe(value => console.log(value));
can be also written like this:
filter((value: string) => value.endsWith('e'))(map(value => value.toString())(of(1, 2, true, false, {a: 'b'})))
.subscribe(a => console.log(a));
Although this is a completely valid RxJS code, there's no way you can think of what it does when you read the latter example. What pipe actually does here is that it reduces over all the functions that were passed in and calls them by passing the previous source Observable to the current function.
Yes. map itself is an operator.
Every operator returns an Observable so later on you can subscribe to the Observable you created.
Of course when I say 'you created' I mean that you created via a creation operator or using the Observable class: new Observable
A pipeable operator is just an operator that would be inside the pipe utility function.
Any function that returns a function with a signature of Observable can be piped and that's why you can create your own Observables and pipe operators to it.
I am pretty much sure that you already know all of this and all you want to know is why there is a conflict in what you are reading.
First, you don't have to pipe anything to your Observable.
You can create an Observable and subscribe to it and that's it.
Since you do not have to pipe anything to your Observable, what should we do with the operators?
Are they used only within a pipe?
Answer is NO
As mentioned, an operator takes configuration options, in your example:
const squareValues = map((val: number) => val * val);
and then it returns a new function that takes the source Observable so you can later on subscribe to it:
const squaredNums = squareValues(nums);
As we can see, map took (val: number) => val * val and returned a function that now gets the Observable nums: const nums = of(1, 2, 3);
Behind the scenes map will take the source observable and transform according to the configuration.
Now the important thing:
Instead of doing that in this way (which you can but no need for that), it is better to pipe your operators so you can combine all of the functions (assuming you are using more operators) into one single function.
So again, behind the scenes you can refer to pipe as a cooler way to make operations on your source Observable rather then declaring many variables that uses different operators with some configuration which return a function that takes a source Observable.

rxjs mapTo operator: evaluate the return value at run time

function c() {
return Math.random();
}
source$.pipe(
map(a => c())
).subscribe(v => console.log(v));
Say there's a simple code like above. What I tried was logging the value when the source stream emits something but obviously, the value I log has nothing to do with the value from the source stream. So it got me considering using mapTo operator like this:
function c() {
return Math.random();
}
source$.pipe(
mapTo(c())
).subscribe(v => console.log(v));
But as you may guess, the value is always the same. More accurately speaking, it stays as the first value which is not what I want.
So my point is, I want the evaluation to be executed each time the source emits a value which I don't use at the evaluation. I can get it working like the first code by using map operator but it just doesn't seem right to use map when I don't use the value from the source stream. Is it okay to use map like this? Or is there any workaround for this kind of matter using mapTo or something else? Any insight would be appreciated!
According to the official definition, mapTo emits the given constant value on the output Observable every time the source Observable emits a value.
Therefore the behavior you described is the expected one. The first evaluation from Math.random() is kept and emitted for every time.
There seems nothing wrong to use map here to get the random values as you expect.

creating lettable rxjs "string.split" operator

I am attempting to do some string manipulation in rjxs, and while I can accomplish it with the built in behaviors on the string class and the array class in Javascript, I'm wanting to use this as an exercise to learn even more about rxjs and understand a fluent code-flow better.
To that end, it's imperative to me that I discover a way to do it that can fit in a fluent solution, instead of a series of variable assignments like I see in most rxjs examples.
Essentially, here's the situation; I've got a string of text;
const example = `
key || value
key || value
key || value
value
value
value
key || key[key1] = value | key[key2] = value
key || value
`;
The first thing that I need to do is use string.split('\n') to create an array of strings, so that I can through each line and perform further operation.
example.string.split('\n') does give the desired results, but trying to send this into rxjs begins to get rather mixed yield. With the pipe method, I know that I send the results into rxjs as an Observable, but I'm having a really troubling time grasping how to truly treat it from there without excessive nesting into the map operator.
For example, if I do ...
of(example.string.split('\n')).pipe(
map(results => results.toString().split('||')),
map(results => ... ),
...
).subscribe();
I can start to get a semblance of what I'm looking for, but what I'd really like to do is ...
of(example).pipe(
split('\n'),
split('||'),
concatMap(results => ...)
).subscribe();
Reading the documentation on lettable operators, seen here, it looks like this should be a pretty easy thing to create. In theory, it should look like this in my mind;
const split = (separator: string) => <T>(source: Observable<T>) =>
new Observable(observer => {
source.subscribe({
next(x) { observer.next(x.toString().split(separator)); },
error(err) { observer.error(err); },
complete() { observer.complete(); }
})
});
So that should make the whole code obvious enough;
of(example).pipe(
split('\n')
).subscribe(result => console.log(`[n]::${result}`));
But this doesn't give me what I really expect. I expected to get an array of the lines, but if I output it, I get ...
[n]::, key || value, key || value, key || value, ,
value, value, , value, key || key[key1] = value |
key[key2] = value, key || value,
I'm really unclear what I'm doing wrong, here. Since it's hard to demonstrate rxjs in most of the code playgrounds like plunkr or jsfiddle, at least to my knowledge, I've prepared a playground environment to demonstrate my work on stackblitz, if it helps.
You'll find all of the pertinent code in the playground/index.ts file. I've done the best I can to abstract away the need to have any knowledge of angular, as I've painstakingly earmarked the sections that should be left alone to make it continue showing output on the right side. If you do not know angular, but can help with rxjs, you should be able to work without ever disturbing that setup.
STACKBLITZ PLAYGROUND
Your code is working fine, just the es6 template string ${} flattened your array into a string. If you console.dir or log the result, you will see a correct array retrieved.

Resources