rxjs operator to define logic after subscribe call - rxjs

const source = Rx.Observable.of(1);
const example = source
.do(val => console.log('do called'));
example.subscribe(val => console.log('subscribe called'));
//Output :
do called
subscribe called
This exemple shows that do is executed before subscribe.
Which operator do I need to use to define logic after subscribe is executed ?
I need this to define logic one time and that must be executed after each subscribe call that helps also to respect SRP (Single responsibility Principle) an example is to handle caching logic in interceptor using some kind of specific operator that I am looking for and subscribe in services

The way I handle an Interceptor is as follows, it may help if I understand your requirements correctly.
...
private interceptor(observable: Observable<Response>): Observable<Response> {
return observable
.map(res => {
return res;
})
.catch((err) => {
//handle Specific Error
return Observable.throw(err);
})
.finally(() => {
//After the request;
console.info("After the Request")
});
}
protected get(req: getHttpParams): Observable<Response> {
return this.interceptor(this.httpClient.get(`${path}/${String(req.id)}`, req.options));
}
...
I would also recommend taking a look at Angular 5's in-built interceptor for http requests specifically

Related

is there a better way to code for two dependent observables

In the method below I want to call two observables. After the data from first observable (getUnrecoveredGearsExt- a http req) is returned I want to pass the data to the second observable (createUpdate- persist to indexDB). Is there a cleaner way to achieve this maybe using some of the rxjs operators. thanks
Note: after the successful completion of the second observable I want to return the data from the first Observable. The use case is get data from the backend and store locally in indexDB and if successful return data or error
public getAndUpdateUnrecoveredGears(cfr: string, maxResults?: number, excludeTripid?: string) : Observable<GearSet[]> {
return Observable.create((observer) => {
this.getUnrecoveredGearsExt(cfr,maxResults,excludeTripid).subscribe(
(gears: GearSet[]) => {
this.createUpdate(gears).subscribe(
() => {
observer.next(gears);
observer.complete();
},
(error) => {
observer.error(error);
}
);
},
(error) => {
observer.error(error);
}
);
});
}
Having nested .subscribe() methods is an anti-pattern of RxJS and can cause many issues. So it's a strong signal of when you need to use operators. Fortunately, there is one which simplifies your code.
public getAndUpdateUnrecoveredGears(cfr: string, maxResults?: number, excludeTripid?: string) : Observable<GearSet[]> {
return this.getUnrecoveredGearsExt(cfr,maxResults,excludeTripid).pipe(
concatMap((gears:GearSet[])=>this.createUpdate(gears))
);
}
Because we're dealing with HTTP requests, they'll emit one value then complete. For this, we can use concatMap(). This operator will wait until getUnrecoveredGearsExt() completes, and then will subscribe to createUpdate() using the value emitted from getUnrecoveredGearsExt(). The operator will then emit any values coming from this "inner observable".
Assuming createUpdate() is also an HTTP request, it will automatically send a complete signal after emitting the response.
The solution below works for me. The final issue was how to pass the previous result 'gears' out as a final result. This is achieved by using the combineLatest to pass the two results to the next map operator, which can then pass gears out.
public getAndUpdateUnrecoveredGearsAlt2(cfr: string, maxResults?: number, excludeTripid?: string): Observable<GearSet[]> {
return this.getUnrecoveredGearsExt(cfr,maxResults,excludeTripid).pipe(
switchMap((gears: GearSet[]) => { return combineLatest(this.createUpdate(gears),of(gears));}),
map(([temp, gears]) => gears )
);
}

Vuex store action from Promise to async/await

Currently I use promises in the store actions but want to convert it into async/await. This is an example of the store action with promises:
fetchActiveWorkspace (context, workspaceID) {
if (workspaceID) {
return this.$axios.get(`#api-v01/workspaces/workspace/${workspaceID}`)
.then(response => {
context.commit('setActiveWorkspace', response.data)
})
.catch(err => {
throw err
})
} else {
return Promise.resolve(true)
}
},
This fetchActiveWorkspace action is resolved in components because it returns promise. How can I convert this code snippet into a async/await structure and use it in components?
This is how I would try to translate it; take into account that as I have no access to the original code in full context, I cannot try it first-hand to make sure it works; but still, this is how you can use async/await with promises.
// 1. Mark the function as `async` (otherwise you cannot use `await` inside of it)
async fetchActiveWorkspace(context, workspaceID) {
if (workspaceID) {
// 2. Call the promise-returning function with `await` to wait for result before moving on.
// Capture the response in a varible (it used to go as argument for `then`)
let response = await this.$axios.get(`#api-v01/workspaces/workspace/${workspaceID}`);
context.commit('setActiveWorkspace', response.data);
}
// 3. I don't think this is necessary, as actions are not meant to return values and instead should be for asynchronous mutations.
else {
return true;
}
}
You can surround the function's body with try/catch in case you want to capture and handle exceptions. I didn't add it in order to keep things simple and because your promise-based code will just capture and re-throw the exception, without doing anything else.

switch final emitted action from effect based on payload

I have an app that uses ngrx
Once a client updates a product, it uses a websocket to update all clients.
This works, by subscribing to the socket, so after a next method is called on the socket, it calls an action that handles the side effects of updating
But, now when it comes to deleting and adding, I'd like to use the same socket effect but change its final action call
Or if someone can suggest a better way
Socket service:
export class SocketService {
socket$ = Observable.webSocket( 'ws://localhost:1234');
}
effects:
//This is called from component to start the update process
#Effect({dispatch:false}) beginUpdate$: Observable<any> = this.actions$
.ofType<fromBlogActions.BlogUpdateStartAction>(fromBlogActions.BLOG_UPDATE_START_ACTION)
.map((action:any)=>{
console.log(action)
return action.payload;
})
.do((action)=> this.socketService.socket$.next(JSON.stringify(action)))
//Calls the next method to send data to the websocket
//The below watches for data emitted from the websocket
//Then calls the BlogUpdatedAction, what I need is for it to call a different action based on action type
#Effect() watchSocket$ = this.socketService.socket$
.map((action:BlogPayLoad)=>{
console.log(action)
return action
})
.mergeMap((action)=> [new fromBlogActions.BlogUpdatedAction(action)])
It should be possible like this:
#Effect() watchSocket$ = this.socketService.socket$
.map((action:BlogPayLoad)=>{
console.log(action)
return action
})
.mergeMap((action)=> {
if(action.type === 'BlogAddAction'){
return new fromBlogActions.BlogAddAction(action))
else if (...) {
....
}
else if (action.type === 'BlogUpdatedAction'){
return new fromBlogActions.BlogUpdatedAction(action))
})

Converting callback hell to observable chain

I have been working with a convention where my functions return observables in order to achieve a forced sequential series of function calls that each pass a returned value to their following "callback" function. But After reading and watching tutorials, it seems as though I can do this better with what I think is flatmap. I think I am close with this advice https://stackoverflow.com/a/34701912/2621091 though I am not starting with a promise. Below I have listed and example that I am hoping for help in cleaning up with advice on a nicer approach. I am very grateful for help you could offer:
grandparentFunction().subscribe(grandparentreturnobj => {
... oprate upon grandparentreturnobj ...
});
grandparentFunction() {
let _self = this;
return Observable.create((observer) => {
...
_self.parentFunction().subscribe(parentreturnobj => {
...
_self.childFunction( parentreturnobj ).subscribe(childreturnobj => {
...
observer.next( grandparentreturnobj );
observer.complete();
});
});
});
}
parentFunction() {
let _self = this;
return Observable.create((observer) => {
...
observer.next( parentreturnobj );
observer.complete();
}
}
childFunction() {
let _self = this;
return Observable.create((observer) => {
...
observer.next( childreturnobj );
observer.complete();
}
}
The general rule-of-thumb in RxJS is that you should really try to avoid creating hand-made, custom Observables (i.e., using Observable.create()) unless you know what you're doing, and can't avoid it. There are some tricky semantics that can easily cause subtle problems if you don't have a firm grasp of the RxJS 'contract', so it's usually better to try to use an existing Observable creation function. Better yet, create Observables via applying operators on an existing Observable, and return that.
In terms of specific critiques of your example code, you're right that you should be using .flatMap() to create Observable function chains. The nested Observable.create()s you currently have are not very Rx-like, and suffer from the same problems 'callback hell'-style code has.
Here's an example of doing the same thing your example does, but in a more idiomatic Rx style. doStuff() is our asynchronous function that we want to create. doStuff() needs to call the asynchronous function step1(), chain its result into the asynchronous function step2(), then do some further operations on the result, and return the final result to doStuff()'s caller.
function doStuff(thingToMake) {
return step1(thingToMake)
.flatMap((step1Result) => step2(step1Result))
.map((step2Result) => {
let doStuffResult = `${step2Result}, and then we're done`;
// ...
return doStuffResult;
});
}
function step1(thingToMake) {
let result = `To make a ${thingToMake}, first we do step 1`;
// ...
return Rx.Observable.of(result);
}
function step2(prevSteps) {
let result = `${prevSteps}, then we do step 2`
// ...
return Rx.Observable.of(result);
}
doStuff('chain').subscribe(
(doStuffResult) => console.log(`Here's how you make a chain: ${doStuffResult}`),
(err) => console.error(`Oh no, doStuff failed!`, err),
() => console.debug(`doStuff is done making stuff`)
)
Rx.Observable.of(x) is an example of an existing Observable creator function. It just creates an Observable that returns x, then completes.

How to dispose nested Rx web request calls in Windows Phone 7

In my application i am using chain of of web request call for fetching data from the net. Ie from the result of one request i will send other request and so on. But when i am disposing the web request, only the parent request is disposing. The two other request are still running. How i can cancel all these request in Rx
For your subscription to terminate everything, you either cannot break the monad or you need to make sure that you work into the IDisposable model.
To keep the monad (ie. stick with IObservables):
var subscription = initialRequest.GetObservableResponse()
.SelectMany(initialResponse =>
{
// Feel free to use ForkJoin or Zip (intead of Merge) to
// end up with a single value
return secondRequest.GetObservableResponse()
.Merge(thirdRequest.GetObservableResponse());
})
.Subscribe(subsequentResponses => { });
To make use of the IDisposable model:
var subscription = initialRequest.GetObservableResponse()
.SelectMany(initialResponse =>
{
return Observable.CreateWithDisposable(observer =>
{
var secondSubscription = new SerialDisposable();
var thirdSubscription = new SerialDisposable();
secondSubscription.Disposable = secondRequest.GetObservableResponse()
.Subscribe(secondResponse =>
{
// Be careful of race conditions here!
observer.OnNext(value);
observer.OnComplete();
});
thirdSubscription.Disposable = thirdRequest.GetObservableResponse()
.Subscribe(thirdResponse =>
{
// Be careful of race conditions here!
});
return new CompositeDisposable(secondSubscription, thirdSubscription);
});
})
.Subscribe(subsequentResponses => { });
One approah is by using TakeUntil extnsion method as described here. In your case, the event that takes this method as parameter could be some event thrown by the parent request.
If you could show us some code we can face the problem more specifically.
regards,

Resources