Search code examples
javascriptfunctional-programmingrxjslodash

Rxjs vs Lodash ? can rxjs be an alternative for lodash?


I know definition and duty of both rxjs and lodash, but I want to know: can I throw out lodash when I use rxjs in my project? because rxjs can works synchronously and asynchronously (async and sync data). I think it can be an alternative for lodash. Am I right?


Solution

  • They are completely different things. But i do understand the confusion: they look comparable, but what to do is very different.

    Lodash: can be compared to Linq in .Net. Its all about navigating, combining and manipulating lists or enumerable things.

    Rxjs: is not about lists, but about events that happen over time.

    It actually makes sense to use them both:

    // every time filter criteria is updated on the GUI, this will emit a new set of filtercriteria
    let filterCriteria$ = new BehaviorSubject<FilterCriteria>({});
    // this gets the list of employees, but will also emit a new set of employees when there are any changes
    let mostRecentListOfEmployees$: Observable<Employee[]> = this.apiService.GetEmployees();
    
    // using combineLatest will make sure that the map operator is executed every time the criteria or the list is updated
    let filteredEmployees$ = filterCriteria$.pipe(
        combineLatest(mostRecentListOfEmployees$),
        map(([filterCriteria, list]) => {
            // this is pseudocode, not sure about the exact lodash syntax for filtering ...
            return _.filter(list, filterCriteria);
        })
    )
    

    You would rely on Rxjs to refilter the list every time the filter criteria is updated, and when a new set of employees comes in via the api.

    Lodash would be used to do the actual filtering on the array.

    Your GUI would subscribe to the filteredEmployees$ observable.

    If this approach seems unfamiliar, this is whats called Reactive Programming: https://en.wikipedia.org/wiki/Reactive_programming