Jasmine-marbles - Is there a expect(...).ToHaveBeenCalledWithObservable(...) function? - jasmine

Is there a way to test observable in a function arguments?
Is there any thing like expect(someObj.foo).ToHaveBeenCalledWithObservable(cold('a|', {a: 1}))?

I don't think there is something that like that but you can maybe take advantage of callFake and toBeObservable.
We callFake and associate a local variable to the argument that was used.
Then we assert the localVariable toBeObservable of your expecation.
let argumentForFoo: Observable<any>;
spyOn(someObj.foo).and.callFake(argument => argumentForFoo = argument);
// make sure someObj.foo gets called somewhere here so the callFake can run.
expect(argumentForFoo).toBeObservable(/*...*/);

Related

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.

Inside a function, how do I construct a new function based on original function parameters, in order to pass as an argument to another function

I'm having trouble with function declarations and scope in julia. I have a main function, let's call it mainfunc which accepts some arguments. Within this function, I would ultimately like to call a different function, say callfunc, which takes a function as an argument. This function I will call passfunc.
One further complication I have is that there is a final function which I define outside of the logic which depends on the arguments but still depends on the arguments in a different way. I can call this initfunc. This must be composed with some other function, depending on the arguments, to create passfunc.
Based on the arguments given to mainfunc, I will have different definitions of passfunc. Given the answer I got to a related question here, I initially tried to define my function logic in the following way, using anonymous functions which are apparently more efficient:
function mainfunc(args)
init_func = x -> funcA(x, args)
if args[1] == "foo"
anon_func = x -> func1(x, args)
elseif args[1] == "bar"
anon_func = x -> func2(x, args)
end
function passfunc(x)
return init_func(x) + anon_func(x)
end
# ... define other args...
callfunc(passfunc, other_args)
end
Defining my function in this way leads to errors in julia - apparently passfunc is an undefined variable when I run this code. Does the scope not allow the anonymous functions to be defined in the if statements? How else could I write code that achieves this?
I feel like a better understanding of functional programming principles would make the solution here obvious. Thank you in advance for any tips you can offer on improving this.
Also, I am running this with julia v0.7

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.

What does it mean to pass `_` (i.e., underscore) as the sole parameter to a Dart language function?

I'm learning Dart and see the following idiom a lot:
someFuture.then((_) => someFunc());
I have also seen code like:
someOtherFuture.then(() => someOtherFunc());
Is there a functional difference between these two examples?
A.k.a., What does passing _ as a parameter to a Dart function do?
This is particularly confusing given Dart's use of _ as a prefix for declaring private functions.
It's a variable named _ typically because you plan to not use it and throw it away. For example you can use the name x or foo instead.
The difference between (_) and () is simple in that one function takes an argument and the other doesn't.
DON’T use a leading underscore for identifiers that aren’t private.
Exception: An unused parameter can be named _, __, ___, etc. This
happens in things like callbacks where you are passed a value but you
don’t need to use it. Giving it a name that consists solely of
underscores is the idiomatic way to indicate the value isn’t used.
https://dart.dev/guides/language/effective-dart/style
An underscore (_) is usually an indication that you will not be using this parameter within the block. This is just a neat way to write code.
Let's say I've a method with two parameters useful and useless and I'm not using useless in the code block:
void method(int useful, int useless) {
print(useful);
}
Since useless variable won't be used, I should rather write the above code as:
void method(int useful, int _) { // 'useless' is replaced with '_'
print(useful);
}
From the Dart Doc - PREFER using _, __, etc. for unused callback parameters.
Sometimes the type signature of a callback function requires a
parameter, but the callback implementation doesn't use the
parameter. In this case, it's idiomatic to name the unused parameter
_. If the function has multiple unused parameters, use additional
underscores to avoid name collisions: __, ___, etc.
futureOfVoid.then((_) {
print('Operation complete.');
});
This guideline is only for functions that are both anonymous and
local. These functions are usually used immediately in a context
where it's clear what the unused parameter represents. In contrast,
top-level functions and method declarations don't have that context,
so their parameters must be named so that it's clear what each
parameter is for, even if it isn't used.
Copy paste the following code in DartPad and hit Run -
void main() {
Future.delayed(Duration(seconds: 1), () {
print("No argument Anonymous function");
});
funcReturnsInteger().then((_) {
print("Single argument Anonymous function " +
"stating not interested in using argument " +
"but can be accessed like this -> $_");
});
}
Future<int> funcReturnsInteger() async {
return 100;
}
That expression is similar to "callbacks" in node.js, the expression have relation to async task.
First remember that => expr expression is shorthand for {return *expr*}, now in someFuture.then((_) => someFunc()), someFuture is a variable of type Future, and this keeps your async task, with the .then method you tell what to do with your async task (once completed), and args in this method you put the callback ((response) => doSomethingWith(response)).
You learn more at Future-Based APIs and Functions in Dart. Thanks
Very common use, is when we need to push a new route with Navigator but the context variable in the builder is not going to be used:
// context is going to be used
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => NewPage(),
));
// context is NOT going to be used
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => NewPage(),
));
I think what people are confusing here is that many think the _ in
someFuture.then((_) => someFunc());
is a parameter provided to the callback function which is wrong, its actually a parameter passed back from the function that you can give a name that you want (except reserved keywords of course), in this case its an underscore to show that the parameter will not be used. otherwise, you could do something like in example given above:((response) => doSomethingWith(response))

Why does ShellTile.ActiveTiles.Count() return different results on immediately subsequent calls?

Consider the following:
IEnumerable<ShellTile> pinnedtiles = ShellTile.ActiveTiles;
Console.WriteLine(pinnedtiles.Count());
Console.WriteLine(pinnedtiles.Count());
Assuming you have more than 0 ActiveTiles, the first call to Count() will return the correct value, but the second call will return 0.
If you dont set ShellTile.ActiveTiles to a local variable, it works fine. I assume this is because ActiveTiles is actually an instance of the internal class ShellTileEnumerator and for some reason, when accessed via the IEnumerable interface, it is acting like a forward-only enumerator. Seems like a likely 'gotcha', or am I misunderstanding something?
Yes you are right
MessageBox.Show(ShellTile.ActiveTiles.Count().ToString());
MessageBox.Show(ShellTile.ActiveTiles.Count().ToString());
The above one will work but not when you assign to IEnumeable .... :)
Another easy way is to assign it toa List instead of IEnumerable . This works too
List<ShellTile> pinnedtiles = ShellTile.ActiveTiles.ToList(); ;
MessageBox.Show(pinnedtiles.Count().ToString());
MessageBox.Show(pinnedtiles.Count().ToString());

Resources