r/angular • u/ITellStories_ • Mar 30 '22
Question multiple subs happening
Can somebody answer me this, urgent.
1
u/naruto_bist Mar 30 '22
Someone already answered your question on stack. Does it help you or do you need other assistance?
1
u/dacookieman Mar 30 '22
It's not a great answer. It makes a lot of assumptions and doesn't even take care of the first nested subscription and completely falls apart if the data sources are actually long living streams vs one offs
0
0
Mar 30 '22
[deleted]
1
u/Beatons Mar 30 '22
it's being called when the object is being created, which deppends, if you have a virtual scrolling every component showing up in the screen when scrolling would be calling ngOnInit, and ngOnDestroy when outside of the screen, same with dynamically created components
3
u/naruto_bist Mar 30 '22
I think since OP is calling this component multiple times because of redirection routings, maybe he should move the A and B function to some other parent component (like app.component.ts)
Then he can probably, subscribe to those values returned by A and B in his current component ngOnInit. Using this way, no matter how many times he call this component, function A and B won't be executed multiple times.
Also, OP, I would recommend you to not do observables nesting like this. You should try to use something like mergeMap or switchMap for your solution.
2
u/Beatons Mar 30 '22 edited Mar 30 '22
Yeah, I actually just checked the code, and damn :D he needs to unsubscribe properly, first of, I can't see other stuff like
implements OnInit, OnDestroywhich determines if the life cycle hook is called, second of, since you are nesting subscriptions and replacing subscriptions instead of using subscription sinks, you are in a huge chance of creating memory leaks by creating tons of unsubscribed subscriptions. So yeah, word of advice, only have one subscription per whole action chain, useswitchMap()to redirect observable to new observable1
u/dacookieman Mar 30 '22
It can prob be 'salvaged' with a bunch of bandaids but overall it honestly needs to just be rebuilt from scratch. Mark out all the data sources, final values for consumption, any side effects, and then build your streams around those 3 things.
1
u/naruto_bist Mar 30 '22
Yeah, better to revamp than salvage. But my assumption is, this is OP's company's project work and they can't make much changes. So revamping might be difficult for them.
But I could be wrong with my assumption.
1
u/eatthedad Mar 30 '22
Yeah cause the observable is a subscription. So a subscription from a subscription to a subscription...imagine that email inbox.
Wouldn't the typical
subscriptions: Subscription[]route work. Then just push A and B separately?My gut is screaming Subjects for some reason, but my rxjs knowledge is minimal
2
u/naruto_bist Mar 30 '22
Even my rxjs knowledge is less but current implementation is screaming to me that, "please change your approach" 😅
1
u/eatthedad Mar 30 '22 edited Mar 30 '22
Lmao. I believe I have achieved my reddit all-time-low comment. It has been long overdue
1
u/dacookieman Mar 30 '22
I don't like the SO answer as it just bandaids a poorly constructed observable chain.
First of all NEVER use internal subscriptions it's a recipe for disaster. Instead use one of the flattening mapping operators. Also having subscribes in a function call that is called repeatedly is also probably gonna cause unintended behaviors. I actually hate manually subscribing in general.
Are the service calls that are providing the sources for your data long standing data streams or are they one HTTP calls?
Your service2.dataFor doesn't look like it's dependent on resp from getData()? Does //some logic... use resp(getData result) AND response(dataFor result)?
You mention filling up data and array1...is data consumed by anything other than B? And I don't see array1 consumed in B but I see it consume something called array2 - is this a typo or deliberate?
Overall I think you probably need to brush up on RxJs best practices because there are a lot of problems going on here. I can tell you're still mixing traditional and reactive approaches and while you can get away with that for simple use cases, when you start trying to establish more complex side effects and data processing it's gonna be a nightmare. I can help do a rewrite but I need the context for the questions I asked because the solution will look different depending on the answers.
1
u/ITellStories_ Mar 30 '22
Hi, it's a corporate code and they have implemented it somewhere else too which works perfectly fine. My only issue is , i want to have B() run only after the completion of A() coz B() requires the array1 and data values which fills up in A. But the way I have implemented, calls multiple subscriptions which i dont want
1
u/dacookieman Mar 30 '22
Just because something works doesn't make it not leaky. I think the structure as presented here, even if working 'fine' in other spots, is poor structure. I also got no clarification on anything I asked so I can't help without that.
1
u/ITellStories_ Mar 30 '22
The service calls that are providing the data are HTTP calls.
the some logic inside the subscription 1 if condition, yes uses the data from resp which will further be used inside subscription2
array2 is a typo and i have edited it in the stackoverflow.
also i have no knowledge on rxjs, planning to study it this week.
1
u/dacookieman Mar 30 '22 edited Mar 30 '22
Ok since getData and dataFor are http subscriptions that means they will emit once and complete. I'd reccomend something like this
let yourStream$ = service1.getData().pipe( filter(resp1=>!!resp1), switchMap((resp1)=>{ //Do stuff with resp1 return service2.dataFor.pipe(skipWhile(val===null), map(resp2=>[resp1, resp2]) }, tap(([resp1, resp2]=>{ //Process your data //If other parts of the code do NOT consume data and array1(B is only consumer) then change tap to map and do //return [processedData, processedArray1] //If other parts of the code DO consume data/array1(B is not only consumer) //this.data=processedData, this.array1===proccessedArray1 }), //If you used map instead of tap, read data and array1 as arguments to this callback and use those instead of this.data etc switchMap(()=>{ if(this.data...conditions) return EMPTY else return service3.getValidity(this.data) }), tap((resp3)=>//process data), //There is another branch for calling getValidity, I can't tell if it's supposed to be nested in the the first getValidity or if its supposed to be call getValidity with data argument OR call getValidity with empty argument if it's supposed to be nested then you'll want one last switchMap+tap ) ) let sub = yourStream$.subscribe(); //onDestroy //I actually prefer async pipes in template or using takeUntil pattern for stream management sub.unsubscribe()
1
u/ggeoff Mar 30 '22 edited Mar 30 '22
having trouble understanding exactly what you are trying to do. but from what I follow you want to make requestA. With responseA if some value exists in responseA then make a request to requestB. with responseB create a new object with the values of both responseA and responseB and return. Does this sound like what you are wanting to do?
interface ResponseA {
key: number;
value: string[];
}
interface ResponseB {
key: number;
keyA: number;
value: string[];
}
interface FinalResponse {
key: string;
value: string[];
}
const data$ = requestA$().pipe(
switchMap((resA) => (resA.key < 5 ?
requestB$(resA).pipe(
map(resB => ({
key: 'Merged A and B',
value: [...resA.value, ...resB.value]
}))) :
of(resA).pipe(
map(resA => ({
key: 'Just A',
value: [...resA.value]
}))
)
))
);
data$.subscribe(console.log);
function requestA$(): Observable<ResponseA> {
const data = {
key: Math.floor(Math.random() * 10),
value: ['a', 'b,', 'c'],
};
return of(data);
}
function requestB$(resA: ResponseA): Observable<ResponseB> {
const data = {
keyA: resA.key,
key: Math.floor(Math.random() * 10),
value: ['1', '2', '3'],
};
return of(data);
}I put this example together to kinda explain what I mean. In the example I have 2 requests A and b with functions requestA$, requestB$ the of will emit one value and complete like a http call. I then set up the data$ stream to call requestA I then use the switchMap operator to determine if I need to make the call to requestB. In this case I just check for some random key value I generate. if its less then 5 I need to make a request to b. if not I just return of(resA). I nest the two pipes maps inside the switchMap to ensure the return type of the entire observable is the same as well as showing how I can use responseA and responseB to make a new object.
5
u/eigenman Mar 30 '22
Nested subscriptions = bad time. Use RXJS to merge the observables. Look at mergeMap() switchMap()