Home > OS >  Is the subscription in constructor fully ran before the subscriptions on ngoninit begin?
Is the subscription in constructor fully ran before the subscriptions on ngoninit begin?

Time:07-23

For example

private subscription: Subscription = new Subscription();


constructor(private userService: UserService) {
    
}

ngOnInit() {

    // I want this the first subscription to fully finish
    // before the 2nd one gets called
    this.subscription.add(userService.someFunc().subscribe((data) => console.log(data))) // 1st
    this.subscription.add(userService.someFunc().subscribe((data) => console.log(data))) // 2nd
}

Since subscribe is async I was wondering how this scenerio works. Is there a chance that ngoninit's subscription finishes first?

If so, is there any way to get constructor's subscription to finish before ngOninit starts?

CodePudding user response:

private destroyed$: ReplaySubject<boolean> = new ReplaySubject(null);
constructor(private userService: UserService) {
    
}

ngOnInit() {
userService.someFunc1().pipe( 
   switchMap((resFromFirst)=>{ return userService.someFunc2()}),
   takeUntil(this.destroyed$)).subsribe((resFromSeconde)=>{})
}

ngOnDestroy() {
    this.destroyed$.next(true);
    this.destroyed$.complete();
}

I am using the takeUntil operator with switchMap.

CodePudding user response:

Simplest answer is to do the second subscription inside the first.

I'm sure one of the suggested rxjs functions in the comments does this in a simpler manner, but for all the years I've been doing Angular, I've gotten myself in a rut of 'this works, whatever' and haven't really gone out of my way to learn all the various parts of the billions of components, services, and frameworks that are available to me.

So you'll have to settle for 'basic but functional' I'm afraid.

public ngOnInit(): void {
    const fn1Sub = this.service.func1().subscribe((res1: any) => {
        fn1Sub.unsubscribe();
        console.log('Function 1 result: ', res1);

        const fn2Sub = this.service.func2().subscribe((res2: any) => {
            fn2Sub.unsubscribe();
            console.log('Function 2 result: ', res2);
        });

    });
}

That's good for one hit when the component loads, assuming that is your desired use case.

  • Related