angelnikolov / ts-cacheable

Observable/Promise Cache Decorator
https://npmjs.com/package/ts-cacheable
ISC License
340 stars 42 forks source link

Refresh data #110

Closed ismailkoksal closed 3 years ago

ismailkoksal commented 3 years ago

Hello, when I'm adding a new item, it don't refresh data

const cacheBuster$ = new Subject<void>();

@Injectable({
  providedIn: 'root',
})
export class CollectsScheduleService {
  constructor(private http: HttpClient) {}

  @Cacheable({
    cacheBusterObserver: cacheBuster$,
  })
  getAll(crematoriumId: number): Observable<CollectSchedule[]> {
    return this.http.get<CollectSchedule[]>(
      `/collect-schedule/crematorium/${crematoriumId}`
    );
  }

  @CacheBuster({
    cacheBusterNotifier: cacheBuster$,
  })
  add(day: Day, zoneId: number): Observable<CollectSchedule> {
    return this.http.post<CollectSchedule>('/collect-schedule', {
      day,
      zoneId,
    });
  }
}
ismailkoksal commented 3 years ago

nvm, I thought it automatically refresh. I need to it manually

ismailkoksal commented 3 years ago

I don't know how refresh data, it still doesn't work.

I tried this:

@CacheBuster({
    cacheBusterNotifier: cacheBuster$,
  })
  add(day: Day, zoneId: number): Observable<CollectSchedule> {
    return this.http.post<CollectSchedule>('/collect-schedule', {
      day,
      zoneId,
    }).pipe(
        tap(() => this.getAll(1))
    );
  }
angelnikolov commented 3 years ago

@ismailkoksal The cache will be cleared once the Observable returned from the method you've decorated with CacheBuster() has emitted. The issue here is that the CacheBuster also works with tap() as you can see here https://github.com/angelnikolov/ts-cacheable/blob/master/cache-buster.decorator.ts#L17. Basically, in your case, your tap() call will be executed before the CacheBuster one, because that was added to the Observable chain at a later stage. Therefore, you will still use the cache.

ismailkoksal commented 3 years ago

@angelnikolov I also tried this

this.collectsScheduleService.add().subscribe(() =>
    this.collectsScheduleService.getAll().subscribe()
);

Still don't work

ismailkoksal commented 3 years ago

Can you provide an example to my code on how to refresh after adding an item please

ismailkoksal commented 3 years ago

This is working

// service.ts

export const cacheBuster$ = new BehaviorSubject<void>(undefined);

@Cacheable({
  cacheBusterObserver: cacheBuster$,
})
getAll(): Observable<any[]> {
  // Return an Observable
}

@CacheBuster({
  cacheBusterNotifier: cacheBuster$,
})
add(): Observable<any> {
  // Return an Observable
}
// component.ts

constructor(private service: Service) {
  this.all$ = cacheBuster$.pipe(switchMap(() => service.getAll()));
}
angelnikolov commented 3 years ago

@ismailkoksal Can you check this example? https://stackblitz.com/edit/ngx-cacheable-my31me?file=src%2Fapp%2Fapp.component.ts We have a get/update/get and it all works. It uses the latest version of ts-cacheable.