Skip to content

Commit

Permalink
refactor: 🛠 refactor MealPlanner in a more reactive way
Browse files Browse the repository at this point in the history
  • Loading branch information
yjaaidi committed Nov 3, 2023
1 parent 9909f32 commit fbf20bb
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions apps/whiskmate/src/app/meal-planner/meal-planner.service.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,58 @@
import { inject, Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { inject, Injectable } from '@angular/core';
import {
BehaviorSubject,
merge,
mergeMap,
Observable,
Subject,
tap,
} from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
import { Recipe } from '../recipe/recipe';
import { MealRepository } from './meal-repository.service';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Injectable({
providedIn: 'root',
})
export class MealPlanner implements OnDestroy {
export class MealPlanner {
recipes$: Observable<Recipe[]>;

private _mealRepository = inject(MealRepository);
private _recipes$ = new BehaviorSubject<Recipe[]>([]);
private _subscription = new Subscription();
private _addRecipe$ = new Subject<Recipe>();

constructor() {
this.recipes$ = this._recipes$.asObservable();
}

ngOnDestroy() {
this._subscription.unsubscribe();
const effects = [
/* Fetch meals from repository. */
this._mealRepository
.getMeals()
.pipe(tap((recipes) => this._recipes$.next(recipes))),
/* Add meals to repository. */
this._addRecipe$.pipe(
mergeMap((recipe) =>
this._mealRepository
.addMeal(recipe)
.pipe(
tap(() => this._recipes$.next([...this._recipes$.value, recipe]))
)
)
),
];

merge(...effects)
.pipe(takeUntilDestroyed())
.subscribe();
}

addRecipe(recipe: Recipe) {
if (!this._canAddRecipe({ recipe, recipes: this._recipes$.value })) {
throw new Error(`Can't add recipe.`);
}

this._subscription.add(this._mealRepository.addMeal(recipe).subscribe());

this._recipes$.next([...this._recipes$.value, recipe]);
this._addRecipe$.next(recipe);
}

watchCanAddRecipe(recipe: Recipe): Observable<boolean> {
Expand Down

0 comments on commit fbf20bb

Please sign in to comment.