Reputation: 61
Can I pass observable to function as a parameter ? I have two observables that get data from backend and I need to filter them out by a lot of conditions. To do not repeat myself I thought about function that will filter observable data and return already filtered one. There will be couple of combineLatest inside as I will be reacting to action streams (values selected on UI). I came up with something like:
const data1$ = this.service.getData('first');
const data2$ = this.service.getData('second');
filterData(input$: Observable<string>) : Observable<string> {
const filtered$ = combineLatest(input$, this.service.selectedFiltersData$).pipe(...filtering...taping and so on...)
const filteredBySomethingElse$(filtered$, this.service.anotherSelectedFilters.pipe(...filtering...taping and so on...)
return filteredBySomethingElse$;
}
const filtered1$ = this.filterData(data1$);
const filtered2$ = this.filterData(data2$);
Example is extremely simplified :)
Is that a good practice ?
Upvotes: 0
Views: 3703
Reputation: 60518
You could use a more declarative approach. Something like this:
// Filtered products
filteredProducts$ = combineLatest([
this.allProducts$,
this.filterAction$])
.pipe(
// Perform the filtering
map(([products, filter]) =>
this.performFilter(products, filter))
);
Then you don't need to pass Observables into procedures. The code that actually does the filtering takes in the products and filter, not their associated observables.
PLUS: The pipe operations will re-execute every time a new value is emitted into either stream.
See this for more information: https://www.youtube.com/watch?v=Z76QlSpYcck
Upvotes: 3