Angular11 value set in service variable gets cleared for subsequent calls - rxjs

I wanted to do conditional http call and got the solution from Angular 11 how to make one of the http request in higher order mapping conditionally
#Injectable({
providedIn: 'root'
})
export class ProjectGuidService {
private projectsGuid = '';
projectGuid$ = this.projectsGuid !== ''
? of(this.projectsGuid)
: this.apiService.get('projects/latest').pipe(
map(({id}) => id),
tap(_ => console.log('current projectsGuid', this.projectsGuid)),
tap(guid => { console.log('tap project guid service', guid); this.projectsGuid = guid; })
);
constructor(
private apiService: ApiService,
private appSettingsService: AppSettingsService
)
{
console.log('project guid service');
//this.projectsGuid = this.appSettingsService.settings.projectId ?? '';
}
}
But in the above solution the http call is made even for the second time ie. even after the first time the value is set to this.projectsGuid.
Not sure what is wrong with it.

this is because the condition will be evaluated only one time.
you set this.apiService.get('projects/latest') in projectGuid$ and alway subscribe to the same, without evaluating it again.
one way to solve your problem is to move the logic in a funcion:
public projectGuid$():Observable<string>{
return this.projectsGuid !== ''
? of(this.projectsGuid)
: this.apiService.get('projects/latest').pipe(
map(({id}) => id),
tap(_ => console.log('current projectsGuid', this.projectsGuid)),
tap(guid => { console.log('tap project guid service', guid); this.projectsGuid = guid; })
);
}
and then you do this.projectGuid$().subscribe(). do not store the result in a variable as you did before.

RxJs provides the shareReplay Operator that does exactlty what you're intending. It repeats the last given value of the Observable.
So if you change your Property declaration to :
projectGuid$ = this.apiService.get('projects/latest').pipe(
map(({ id }) => id),
shareReplay(1)
);
The this.apiService.get('projects/latest') gets only called once, even for multiple Observers.

Related

How to remove element from BehaviorSubject array?

There is an array in public users = new BehaviorSubject<User[]>([]).
I want to delete element from this observable and refresh it.
My solution is:
const idRemove = 2;
this.users.next(this.user.getValue().filter((u) => u.id !== idRemove)
But I seem I use wrong way of using RXJS
Toward Idiomatic RxJS
Using subscribe instead of .value.
interface User {
id: number
}
const users$ = new BehaviorSubject<User[]>([
{id:1},
{id:2},
{id:3}
]);
function removeId(idRemove: number) {
users$.pipe(
take(1),
map(us => us.filter(u => u.id !== idRemove))
).subscribe(
users$.next.bind(users$)
);
}
users$.subscribe(us =>
console.log("Current Users: ", us)
);
removeId(2);
removeId(1);
removeId(3);
Output:
Current Users: [ { id: 1 }, { id: 2 }, { id: 3 } ]
Current Users: [ { id: 1 }, { id: 3 } ]
Current Users: [ { id: 3 } ]
Current Users: []
To handle state within RxJS pipes you can use the Scan operator
Useful for encapsulating and managing state. Applies an accumulator (or "reducer function") to each value from the source after an initial state is established -- either via a seed value (second argument), or from the first value from the source.
const { Subject, merge } = rxjs;
const { scan, map } = rxjs.operators;
// This function is used to apply new users to the state of the scan
const usersFn = users => state => users
// This function is used to remove all matching users with the given id from the state of the scan
const removeFn = removeId => state => state.filter(user => user.id !== removeId)
// This Subject represents your old user BehaviorSubject
const users$$ = new Subject()
// This Subject represents the place where this.users.next(this.user.getValue().filter((u) => u.id !== idRemove) was called
const remove$$ = new Subject()
// This is your new user$ Observable that handles a state within its pipe. Use this Observable in all places where you need your user Array instead of the user BehaviorSubject
const user$ = merge(
// When users$$ emits the usersFn is called with the users argument (1. time)
users$$.pipe(map(usersFn)),
// When remove$$ emits the removeFn is called with the removeId argument (1. time)
remove$$.pipe(map(removeFn))
).pipe(
// Either the usersFn or removeFn is called the second time with the state argument (2. time)
scan((state, fn) => fn(state), [])
)
// Debug subscription
user$.subscribe(console.log)
// Test emits
users$$.next([
{id: 1, name: "first"},
{id: 2, name: "second"}
])
remove$$.next(2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.4.0/rxjs.umd.min.js"></script>
Ben Lesh (main Contributor of RxJS) wrote an anser about why not to use getValue in RxJS: The only way you should be getting values "out of" an Observable/Subject is with subscribe!
Using getValue() is discouraged in general for reasons explained here even though I'm sure there are exception where it's fine to use it. So a better way is subscribing to get the latest value and then changing it:
this.users
.pipe(take(1)) // take(1) will make sure we're not creating an infinite loop
.subscribe(users => {
this.users.next(users.filter((u) => u.id !== idRemove);
});

What operator is used to get several values from observable

return this.usersTableService.fetchRequestedPageUsersIds(request).pipe(
switchMap((idsToFetch) => {
requestedIds = idsToFetch;
return [this.usersTableService.getNewIdsToFetch(requestedIds, entities), of(idsToFetch)];
}),
//.......?(([newIds, idsToFetch]) => {
return this._fetchNewUsersFromAPI(requestedIds, request, newIds, entities);
}),
catchError((err) => of(loadPageFail(err)))
);
what operator should I use in order to get the value of the return tuple before ?
You can use forkJoin for this
return this.usersTableService.fetchRequestedPageUsersIds(request).pipe(
switchMap((idsToFetch) => {
return forkJoin([this.usersTableService.getNewIdsToFetch(requestedIds, entities), of(idsToFetch)]);
}),
mergeMap(([newIds, idsToFetch]) => {
return this._fetchNewUsersFromAPI(requestedIds, request, newIds, entities);
}),
catchError((err) => of(loadPageFail(err)))
)
You would normally use the map operator(https://stackblitz.com/edit/so-tuple-map?file=index.ts):
const obs$ = of(1).pipe(map(y => ['abc', 'def']), map(([str1, str2]) => str1 + str2))
But if you try that you will encounter other issues with your code ie:
its not good practice to store a local variable inside a switchMap then return it using of
_fetchNewUsersFromAPI needs to be inside a switchMap
Ultimately you'll still be faced with the fundamental problem of how to pass parameters down the observable chain, which I suspect is how you've ended up in this situation to begin with.
There is currently a bountied question asking about the same problem here: How to pass results between chained observables
IMO the best solution from that question is to use nested pipes ie:
const newUsers$ = requestsSubject.pipe(
switchMap(request =>
this.usersTableService.fetchRequestedPageUsersIds(request).pipe(
switchMap(idsToFetch =>
this.usersTableService.getNewIdsToFetch(idsToFetch).pipe(
switchMap(newIds =>
this._fetchNewUsersFromAPI(idsToFetch, request, newIds, entities)
)
)
)
)
)
);
An alternative way using await and toPromise:
function getUsers(request){
const idsToFetch = await this.usersTableService.fetchRequestedPageUsersIds(request).toPromise();
const newIds = await this.usersTableService.getNewIdsToFetch(idsToFetch, entities).toPromise();
const newUsers = await this._fetchNewUsersFromAPI(idsToFetch, request, newIds, entities).toPromise();
return newUsers;
}

how to use multicasting obs with behavioursubject?

In general we need behavior subject functionality. But only on first subscription we should send subscribe to server in REST. And to send unsubscribe on the last unsubscribe, and all late observers subscribed will gwt the latest json recwived from the first. can i do it using rxjs operaTors and how? or shoul i use custom obserbale ?
currently the custom code for this is this:
public observable: Observable<TPattern> = new Observable((observer: Observer<TPattern>) => {
this._observers.push(observer);
if (this._observers.length === 1) {
this._subscription = this.httpRequestStream$
.pipe(
map((jsonObj: any) => {
this._pattern = jsonObj.Data;
return this._pattern;
})
)
.subscribe(
(data) => this._observers.forEach((obs) => obs.next(data)),
(error) => this._observers.forEach((obs) => obs.error(error)),
() => this._observers.forEach((obs) => obs.complete())
);
}
if (this._pattern !== null) {
observer.next(this._pattern); // send last updated array
}
return () => {
const index: number = this._observers.findIndex((element) => element === observer);
this._observers.splice(index, 1);
if (this._observers.length === 0) {
this._subscription.unsubscribe();
this._pattern = null; // clear pattern when unsubscribed
}
};
});
Sounds like you need a shareReplay(1), it will share the latest response with all subscribes.
const stream$ = httpRequestStream$.pipe(
shareReplay(1),
),
stream$.subscribe(); // sends the request and gets its result
stream$.subscribe(); // doesn't send it but gets cached result
stream$.subscribe(); // doesn't send it but gets cached result
stream$.subscribe(); // doesn't send it but gets cached result

Why I can't dispatch multiple action with a map?

I am trying to understand something Inside my epic
const loginEpic = (action$, state$) => action$.pipe(
ofType(UsersActions.loginRequest),
switchMap((action: {payload:{email: string, password: string}}) =>
HttpService.PostAsync<apiModels.api_token_auth_request, apiModels.api_token_auth_response>('token-auth', action.payload).pipe(
switchMap(response => {
let token = response && response.data && response.data.token ? response.data.token : '';
return of(
UsersActions.setUserAuth({authKey: token}),
UsersActions.loginSuccess(),
WorkspaceActions.getWorkspacesRequest()
);
}),
catchError((error: string) => {
return of(UsersActions.loginFailed({error}));
})
)
)
);
Why this works
switchMap(response => {
let token = response && response.data && response.data.token ? response.data.token : '';
return of(
UsersActions.setUserAuth({authKey: token}),
UsersActions.loginSuccess(),
WorkspaceActions.getWorkspacesRequest()
);
}),
But this will not work
map(response => {
let token = response && response.data && response.data.token ? response.data.token : '';
return concat(
of(UsersActions.setUserAuth({authKey: token})),
of(UsersActions.loginSuccess()),
of(WorkspaceActions.getWorkspacesRequest())
);
}),
Uncaught Error: Actions must be plain objects. Use custom middleware
for async actions.
Isn't the second one also a first stream ?
switchMap will subscribe to the inner Observable returned (in this case of) and reemit all its items. So of emits 3 items that are propagated further.
On the other hand, map just takes the value returned from its "project" function and propagates it further. map doesn't care what the returned value is. No further logic is applied.
So in your case map is propagating an instance of Observable which is not a valid action.

Subscribe two times to one observable

first func:
updateMark(item: MarkDTO) {
this.service
.put(item, this.resource)
.subscribe(() => this.markEdit = null);
}
second func:
put(item: MarkDTO, rcc: string): Observable<MarkDTO> {
const rdto = new MarkRDTO(item);
const url = `${this.getUrl('base')}${rcc}/marks/${rdto.rid}`;
const obs = this.http.put<MarkDTO>(url, rdto, { withCredentials: true })
.pipe(map((r: MarkDTO) => new MarkDTO(r)))
.share();
obs.subscribe(newMark => this.storage.update(newMark, rcc));
return obs;
}
in service i need to update data after request
but also in same time i need to clear current editItem
all of it must be done after i subscribe to one httpRequest
.share() - suport from rxjs-compat package (i want to remove this dep in closest time)
without .share() - work only 1 of 2 steps
current rxjs version is 6.3.3
Help who can...
There is a pipeable share operator, that you would use the same way you use map() (i.e. inside pipe()) and thus doesn't need rxjs-compat.
But you don't need share() here. All you need is the tap() operator:
put(item: MarkDTO, rcc: string): Observable<MarkDTO> {
const rdto = new MarkRDTO(item);
const url = `${this.getUrl('base')}${rcc}/marks/${rdto.rid}`;
return this.http.put<MarkDTO>(url, rdto, { withCredentials: true })
.pipe(
map(r => new MarkDTO(r)),
tap(newMark => this.storage.update(newMark, rcc))
);
}

Resources