Mixing an action stream (such as adding an action) with your data stream allows for a seamless flow of adding items to your stream by incorporating them into the action stream.
Here is a customizable example that showcases this concept:
// Retrieve all products
products$ = this.http.get<Product[]>(this.productsUrl)
.pipe(
tap(data => console.log('Products', JSON.stringify(data))),
catchError(this.handleError)
);
// Action Stream
private productInsertedSubject = new Subject<Product>();
productInsertedAction$ = this.productInsertedSubject.asObservable();
// Merge the streams
productsWithAdd$ = merge(
this.products$,
this.productInsertedAction$
)
.pipe(
scan((acc: Product[], value: Product) => [...acc, value]),
catchError(err => {
console.error(err);
return throwError(err);
})
);
addProduct(newProduct: Product) {
this.productInsertedSubject.next(newProduct);
}
To add more items (in this case, products), simply utilize the addProduct
function and provide the necessary input.
LATEST UPDATE: I have adjusted the code above to better suit your specific requirements:
results = [];
// Data stream
urls$ = from(this.generateUrls());
// Action Stream
private newUrlSubject = new Subject<string>();
newUrlAction$ = this.newUrlSubject.asObservable();
// Merge the streams
urlsWithAdd$ = merge(
this.urls$,
this.newUrlAction$
)
.pipe(
tap(url => console.log('url:', url)),
mergeMap(url => this.http.get(url), 4),
tap(result => this.results.push(result))
);
constructor(private http: HttpClient, ) {
this.urlsWithAdd$.subscribe();
}
generateUrls() {
let urls = [];
for (let i = 1; i <= 20; i++) {
urls.push(`https://jsonplaceholder.typicode.com/todos/${i}`);
}
return urls;
}
addUrl(newUrl: string) {
this.newUrlSubject.next(newUrl);
}
onClick() {
this.addUrl(`https://jsonplaceholder.typicode.com/todos/42`);
}
The complete code can be accessed here: https://stackblitz.com/edit/angular-rxjs-adding-items-deborahk
PLEASE NOTE: The use of fetch
was not viable due to its promise-based nature, unlike Observables. However, you could explore alternatives like from(fetch(...))
?