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 8725a72
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 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,48 @@
import { inject, Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { inject, Injectable } from '@angular/core';
import {
BehaviorSubject,
merge,

Check warning on line 4 in apps/whiskmate/src/app/meal-planner/meal-planner.service.ts

View workflow job for this annotation

GitHub Actions / βœ… Test

'merge' is defined but never used
mergeMap,
Observable,
Subject,
tap,

Check warning on line 8 in apps/whiskmate/src/app/meal-planner/meal-planner.service.ts

View workflow job for this annotation

GitHub Actions / βœ… Test

'tap' is defined but never used
} 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();
this._addRecipe$
.pipe(
mergeMap((recipe) =>
this._mealRepository.addMeal(recipe).pipe(map(() => recipe))
),
takeUntilDestroyed()
)
.subscribe((recipe) =>
this._recipes$.next([...this._recipes$.value, recipe])
);
}

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 8725a72

Please sign in to comment.