Where are intervals stored? - rxjs

If I fire the following function 10 times
createInterval() {
var someInterval = interval(10000).pipe( take(1)).subscribe(
_intervalValue =>
{
console.log(" Interval Fired" + new Date().toISOString());
});
}
I get 10 intervals that will console log 10 times. How do I know that I have 10 intervals?
Where can I access these, it's like they exist mysteriously somewhere.

How do I know that I have 10 intervals?
Let's simplify using numbers instead of Observables:
function createNumber() {
const someNumber = Math.random();
console.log(`Number Created: ${someNumber}`);
}
for(let x=0; x<10; x++) {
createNumber();
}
And re-ask the same question: "How do I know that I have 10 numbers?"
Well... you don't. Not unless you're saving a reference to them!
So let's have the function return a reference to the number:
function createNumber() {
const someNumber = Math.random();
console.log(`Number Created: ${someNumber}`);
return someNumber;
}
let myNumbers = [];
for(let x=0; x<10; x++) {
myNumbers.push(createNumber());
}
console.log(`I know I have ${myNumbers.length} numbers!`);
This behavior is no different for observables. If you want know you have 10 intervals, you need to keep track of them:
function createInterval() {
return interval(1000)
.pipe(take(1))
.subscribe(
() => console.log(`Interval Fired: ${ new Date().toISOString() }`)
);
}
let mySubscriptions: Subscription[] = [];
for(let x=0; x<10; x++) {
mySubscriptions.push(createInterval());
}
mySubscriptions.forEach(
sub => sub.unsubscribe()
);
Note: by calling .subscribe() you are returning a Subscription, not an Observable. It is often convenient to have functions return the observable, and let consumers of the function call .subscribe():
function createInterval() {
return interval(1000).pipe(
take(1),
tap(() => console.log(`Interval Fired: ${ new Date().toISOString() }`))
);
}
let myObservables: Observable<number>[] = [];
for(let x=0; x<10; x++) {
myObservables.push(createInterval());
}
const mySubscriptions = myObservables.map(
obs => obs.subscribe()
);
// then later on, you can unsubscribe
mySubscriptions.forEach(
sub => sub.unsubscribe()
);

Related

How to get results using a loop inside of switch map

I have the next code, and it was working properly. to execute a request to my method fetchDropdownDataByFederationId, but now I have a requirement to execute the same method x number of times.
fetchInProgress(queryString?): Observable<IPerson[]> {
let PersonList: IPerson[] = [];
return this.getItems<IPerson[]>('', queryString).pipe(
take(1),
switchMap((wls: IPerson[]) => {
PersonList = [...wls];
//const createdbyIds = [...new Set(wls.map((f) => f.createdBy))];
return this.teamPageService.getInformation(wls.createdBy);
}),
map((teams:any) => {
console.log('> teams', teams);
for (let i = 0; i < PersonList.length; i++) {
//update information
}
//console.log('> Final value: ', PersonList);
return PersonList;
})
);
}
But, I'm not finding a way to execute my SwitchMap x number of times and get the results back to use them in my map method to parse the information.
I just moved my SwitchMap to mergeMap, something like this:
mergeMap((wls: IWalklist[]) => {
//let allIds = wls.contact.map(id => this.getSingleData(id._id) );
let drops: Dropdown[] = [];
walklistList = [...wls];
const allIds = [...new Set(wls.map((f) => f.createdBy))];
return forkJoin(...allIds).pipe(
map((idDataArray) => {
drops.push(
this.teamPageService.getInformation('');
);
return drops;
})
)
}),
But still no luck.
Can some help me? how can I fix it?

Do something if RxJs subject's refCount drops to zero

I'm working on a service layer that manages subscriptions.
I provide subject-backed observables to consumers like this:
const subject = new Subject();
_trackedSubjects.push(subject);
return subject.asObservable();
Different consumers may monitor the channel, so there may be several observables attached to each subject.
I'd like to monitor the count of subject.observers and if it ever drops back to 0, do some cleanup in my library.
I have looked at refCount, but this only is available on Observable.
I'd love to find something like:
subject.onObserverCountChange((cur, prev) =>
if(cur === 0 && prev !== 0) { cleanUp(subject) }
)
Is there a way to automatic cleanup like this on a subject?
Instead of using Subject - you should probably describe setup/cleanup logic when creating observable. See the example:
const { Observable } = rxjs; // = require("rxjs")
const { share } = rxjs.operators; // = require("rxjs/operators")
const eventSource$ = Observable.create(o => {
console.log('setup');
let i = 0
const interval = setInterval(
() => o.next(i++),
1000
);
return () => {
console.log('cleanup');
clearInterval(interval);
}
});
const events$ = eventSource$.pipe(share());
const first = events$.subscribe(e => console.log('first: ', e));
const second = events$.subscribe(e => console.log('second: ', e));
setTimeout(() => first.unsubscribe(), 3000);
setTimeout(() => second.unsubscribe(), 5000);
<script src="https://unpkg.com/rxjs#6.2.2/bundles/rxjs.umd.min.js"></script>

Multiple rxjs http requests Angular 6

I have following code:
private getUsers(page, result) {
result = result||[];
return this.http.get(API_URL + '/users?page=1')
.pipe(map(response => {
const response_filter = response.json();
const users = response_filter['data'];
const pages = response_filter['total_pages'];
Array.prototype.push.apply(result, users.map((user) => new User(user)));
while (page != pages)
{
this.http.get(API_URL + '/users?page=' + page)
.pipe(map(resp => {
console.log('test');
const response_filter = resp.json();
const users = response_filter['data'];
Array.prototype.push.apply(result, users.map((user) => new User(user)));
return result;
}))
.pipe(catchError(val => of(`Caught inner error: ${val}`)));
page += 1;
}
return result;
}))
.pipe(catchError(val => of(`Caught error: ${val}`)));
}
Code works good until console.log('test'). This log doesn't get shown, but while loop iterates fine.
Previously i tried the same function, but in recursive way. There was the same problem.
The best way to do this is to create a single observable which represents all of the requests you want to make, using flatMap and forkJoin operators. There are a number of problems with the asynchronous operations in your code, meaning that the returned result will not include the results of the inner HTTP requests.
I would propose the following:
private getUsers(page, result) {
return this.http.get(API_URL + '/users?page=1')
.pipe(
flatMap((response) => {
const response_filter = response.json();
const users = response_filter['data'];
const pages = response_filter['total_pages'];
let firstPageUsers: User[] = users.map((user) => new User(user));
let getAllUsers: Observable<User[]>[];
getAllUsers.push(of(firstPageUsers));
while (page < pages)
{
getAllUsers.push(this.http.get(API_URL + '/users?page=' + page)
.pipe(
map(resp => {
console.log('test');
const response_filter = resp.json();
const users = response_filter['data'];
return users.map((user) => new User(user));
}),
// You need to decide if this is how you want errors
// handled, it doesn't seem too sensible to me:
catchError((err) => {
console.log(`Caught inner error: ${err}`);
return of([]); // needs to return type Observable<User[]>
})
)
);
page += 1;
}
return forkJoin(getAllUsers);
}),
map((allResponses) => {
// allResponses will be an array of User arrays from
// all of the observables within the forkJoin, so now
// we can iterate over all of those to create a single
// array containing all of the results.
result = result||[];
allResponses.forEach((responseUsers) => {
Array.prototype.push.apply(result, responseUsers);
});
return result;
}),
catchError((err) => {
console.log(`Caught outer error: ${err}`);
of(null); // Or whatever - again, think about your error cases.
})
);
}
Now wherever you are calling getUsers, when you subscribe to this observable it should resolve all of the inner queries as well.
Marks answer is great, but I already solved my problem (maybe not in the good way, but solved it) using Martin comment (using subscribe). Firstly I subscribe for a "get pages count" request and then I'm subscribing to "get users" request in a while loop.
I'm new in angular, so maybe someone will answer a question "Must I use unsubscribe here?"
this._dataSub0 = this.userDataService.getPages().subscribe((pages) => {
var page_num = pages;
var i = 1;
while (i < page_num) {
this._dataSub = this.userDataService
.getAllUsers()
.subscribe(
(users) => {
for (let us of users) {
this.users.push(us);
}
}
);
i++;
}
});
public getAllUsers(page): Observable<User[]> {
return this.getUsers(page);
}
private getUsers(page) {
var result = result||[];
return this.http.get(API_URL + '/users?page=' + page)
.pipe(map(response => {
const response_filter = response.json();
const users = response_filter['data'];
const pages = response_filter['total_pages']
if(pages == page)
return null;
Array.prototype.push.apply(result, users.map((user) => new User(user)));
return result;
}))
.pipe(catchError(val => of(`Caught error: ${val}`)));
}
public getPages(): Observable<number> {
var result;
return this.http.get(API_URL + '/users?page=0')
.pipe(map(response => {
const response_filter = response.json();
const pages = response_filter['total_pages']
return pages;
}))
.pipe(catchError(val => of(`Caught error: ${val}`)));
}

How to batch additions to arrays/lists returned by rxjs observables?

have an observable that returns arrays/lists of things: Observable
And I have a usecase where is is a pretty costly affair for the downstream consumer of this observable to have more items added to this list. So I'd like to slow down the amount of additions that are made to this list, but not loose any.
Something like an operator that takes this observable and returns another observable with the same signature, but whenever a new list gets pushed on it and it has more items than last time, then only one or a few are added at a time.
So if the last push was a list with 3 items and next push has 3 additional items with 6 items in total, and the batch size is 1, then this one list push gets split into 3 individual pushes of lists with lengths: 4, 5, 6
So additions are batched, and this way the consumer can more easily keep up with new additions to the list. Or the consumer doesn't have to stall for so long each time while processing additional items in the array/list, because the additions are split up and spread over a configurable size of batches.
I made an addAdditionalOnIdle operator that you can apply to any rxjs observable using the pipe operator. It takes a batchSize parameter, so you can configure the batch size. It also takes a dontBatchAfterThreshold, which stops batching of the list after a certain list size, which was useful for my purposes. The result also contains a morePending value, which you can use to show a loading indicator while you know more data is incomming.
The implementation uses the new requestIdleCallback function internally to schedule the batched pushes of additional items when there is idle time in the browser. This function is not available in IE or Safari yet, but I found this excelent polyfill for it, so you can use it today anyways: https://github.com/aFarkas/requestIdleCallback :)
See the implementation and example usage of addAdditionalOnIdle below:
const { NEVER, of, Observable } = rxjs;
const { concat } = rxjs.operators;
/**
* addAdditionalOnIdle
*
* Only works on observables that produce values that are of type Array.
* Adds additional elements on window.requestIdleCallback
*
* #param batchSize The amount of values that are added on each idle callback
* #param dontBatchAfterThreshold Return all items after amount of returned items passes this threshold
*/
function addAdditionalOnIdle(
batchSize = 1,
dontBatchAfterThreshold = 22,
) {
return (source) => {
return Observable.create((observer) => {
let idleCallback;
let currentPushedItems = [];
let lastItemsReceived = [];
let sourceSubscription = source
.subscribe({
complete: () => {
observer.complete();
},
error: (error) => {
observer.error(error);
},
next: (items) => {
lastItemsReceived = items;
if (idleCallback) {
return;
}
if (lastItemsReceived.length > currentPushedItems.length) {
const idleCbFn = () => {
if (currentPushedItems.length > lastItemsReceived.length) {
observer.next({
morePending: false,
value: lastItemsReceived,
});
idleCallback = undefined;
return;
}
const to = currentPushedItems.length + batchSize;
const last = lastItemsReceived.length;
if (currentPushedItems.length < dontBatchAfterThreshold) {
for (let i = 0 ; i < to && i < last ; i++) {
currentPushedItems[i] = lastItemsReceived[i];
}
} else {
currentPushedItems = lastItemsReceived;
}
if (currentPushedItems.length < lastItemsReceived.length) {
idleCallback = window.requestIdleCallback(() => {
idleCbFn();
});
} else {
idleCallback = undefined;
}
observer.next({
morePending: currentPushedItems.length < lastItemsReceived.length,
value: currentPushedItems,
});
};
idleCallback = window.requestIdleCallback(() => {
idleCbFn();
});
} else {
currentPushedItems = lastItemsReceived;
observer.next({
morePending: false,
value: currentPushedItems,
});
}
},
});
return () => {
sourceSubscription.unsubscribe();
sourceSubscription = undefined;
lastItemsReceived = undefined;
currentPushedItems = undefined;
if (idleCallback) {
window.cancelIdleCallback(idleCallback);
idleCallback = undefined;
}
};
});
};
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
let testSource = of(
[1,2,3],
[1,2,3,4,5,6],
).pipe(
concat(NEVER)
);
testSource
.pipe(addAdditionalOnIdle(2))
.subscribe((list) => {
// Simulate a slow synchronous consumer with a busy loop sleep implementation
sleep(1000);
document.body.innerHTML += "<p>" + list.value + "</p>";
});
<script src="https://unpkg.com/rxjs#6.5.3/bundles/rxjs.umd.js"></script>

Wait for n executions of a method and then continue after complete

I have a function that returns promise:
Setup.zoomIn() : Promise<void> {...}
I would like to use rxjs to invoke that function 5 times with delay of 1 second between each, like this:
let obs = Observable.create(observer => {
let count = 0;
setTimeout(() => {
Setup.zoomIn();
count++;
observer.next();
}, 1000);
if (count === 5) {observer.complete();}
};
obs.subscribe(() =>
console.log('zoomed out');
)};
Only and only when that is executed I would like to continue with execution to perform further steps:
obs.toPromise.then(() => {
// do some stuff here but only after zoom has been invoked 5 times
})
Create a list of observables for zoomIns functions and concat them with another Observable.
function zoomIn(i) {
return new Promise(res => {
setTimeout(()=>res(i), 1000);
});
};
function anotherPromise() {
return Rx.Observable.defer(()=> {
return new Promise(res => {
setTimeout(()=>res('anotherPromise'), 3000);
});
});
}
const zoonInList = Array(5).fill(0).map((x, i)=>i).map(i=>
Rx.Observable.defer(()=> {
return zoomIn(i);
})
);
Rx.Observable.concat(...zoonInList, anotherPromise())
.subscribe(x=>console.log(x))

Resources