Skip to content

Commit c4f7a66

Browse files
committed
fix: fix deleteOldTopics logic
1 parent 543770b commit c4f7a66

2 files changed

Lines changed: 37 additions & 9 deletions

File tree

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { inject, Injectable } from '@angular/core';
2-
import { merge, Observable, of } from 'rxjs';
2+
import { catchError, forkJoin, map, Observable, of, tap } from 'rxjs';
33
import { LocalDBService, TopicType } from './localDB.service';
44

55
@Injectable({ providedIn: 'root' })
@@ -10,10 +10,38 @@ export class AppService {
1010

1111
deleteOldTopics(type: TopicType): Observable<boolean> {
1212
const infoByType = this.dbService.searchByType(type);
13-
return infoByType.length > 0
14-
? infoByType
15-
.map((t) => this.dbService.deleteOneTopic(t.id))
16-
.reduce((acc, curr) => merge(acc, curr), of(true))
17-
: of(true);
13+
14+
if (!infoByType?.length) {
15+
return of(true);
16+
}
17+
18+
const requests$ = infoByType.map((t) =>
19+
this.dbService.deleteOneTopic(t.id).pipe(
20+
tap((result) => {
21+
if (result) {
22+
console.log(`${type} with id ${t.id} deleted successfully.`);
23+
} else {
24+
console.error(`Failed to delete ${type} with id ${t.id}.`);
25+
}
26+
}),
27+
catchError((error) => {
28+
console.error(
29+
`There was an error while deleting ${type} with id ${t.id}.`,
30+
error,
31+
);
32+
return of(false);
33+
}),
34+
),
35+
);
36+
37+
return forkJoin(requests$).pipe(
38+
tap((results) =>
39+
console.log(
40+
`All deletion requests for ${type} completed with results:`,
41+
results,
42+
),
43+
),
44+
map((results) => results.every((r) => r)),
45+
);
1846
}
1947
}

apps/rxjs/11-high-order-operator-bug/src/app/localDB.service.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* eslint-disable @typescript-eslint/member-ordering */
22
import { randomError } from '@angular-challenges/shared/utils';
33
import { computed, Injectable, signal } from '@angular/core';
4-
import { of } from 'rxjs';
4+
import { Observable, of, throwError } from 'rxjs';
55

66
export type TopicType = 'food' | 'book' | 'sport';
77

@@ -42,12 +42,12 @@ export class LocalDBService {
4242
this.state.set({ infos: this.state().infos.filter((i) => i.id !== id) });
4343
};
4444

45-
deleteOneTopic = (id: number) =>
45+
deleteOneTopic = (id: number): Observable<boolean> =>
4646
randomError({
4747
success: () => {
4848
this.deleteOne(id);
4949
return of(true);
5050
},
51-
error: () => of(false),
51+
error: () => throwError(() => new Error('Random error occurred')),
5252
});
5353
}

0 commit comments

Comments
 (0)