Skip to content

Instantly share code, notes, and snippets.

@serjKim
Created April 18, 2022 09:08
Show Gist options
  • Save serjKim/b4ce965d702f5e1c6a2eebc7806213dc to your computer and use it in GitHub Desktop.
Save serjKim/b4ce965d702f5e1c6a2eebc7806213dc to your computer and use it in GitHub Desktop.
rxjs storage
class UserStorage {
private readonly reload$ = new Subject<void>();
private readonly userId$ = new ReplaySubject<number>(1);
public readonly user: Observable<string>;
constructor() {
this.user = combineLatest([
this.reload$.pipe(startWith(undefined)),
this.userId$
]).pipe(
switchMap(([_, userId]) => this.loadUser(userId)),
shareReplay({ bufferSize: 1, refCount: true }),
);
}
public load(userId: number) {
this.userId$.next(userId);
}
public reload(): void {
this.reload$.next();
}
private loadUser(userId: number): Observable<string> {
return of(`user loaded with ${userId}`).pipe(tap(() => console.log('loading...')))
}
}
const userStorage = new UserStorage();
userStorage.load(1);
userStorage.user.subscribe(x => {
console.log(`1: `, x);
});
userStorage.user.subscribe(x => {
console.log(`2: `, x);
});
// userStorage.load(2);
// setTimeout(() => {
// userStorage.reload();
// userStorage.reload();
// userStorage.reload();
// }, 700)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment