Created the component with multiple subscription, also on ngOnDestroy doing the unsubscribe.
It's working as expected but created the multiple variable for each subscription, how can i do with single variable like pushing in to array or json?
tried below logic
this.sub[1] = this.crossCommunicate.toggleEdit.subscribe(
(showedit: any) => {
this.showedit = showedit;
}
);
Pushed all the subscribes by key value, if any key value missing or mismatched may error come.
ngOnDestroy() {
for(let i=1; i < this.sub.length ; i++){
this.sub[i].unsubscribe();
}
}
Is the any better way to implement this?
You can create one Subscription
object and add everything into it using its add
method.
this.subscriptions = new Subscription();
const sub1 = this.whatever$.subscribe(...);
const sub2 = this.foobar$.subscribe(...);
this.subscriptions
.add(sub1)
.add(sub2);
And then unsubscribe everything:
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
Maybe a also have a look at this: https://github.com/ReactiveX/rxjs/issues/2769
Use TakeUntil:
import 'rxjs/add/operator/takeUntil';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
export class APPcomponent implements OnInit, OnDestroy {
private ngUnsubscribe: Subject<any> = new Subject();
}
ngOnInit() {
this.someService.SomeCall(parametesr)
.takeUntil(this.ngUnsubscribe)
.subscribe(
data => {
some result
},
error => { },
() => {
});
this.someService.SecondCall(parametesr)
.takeUntil(this.ngUnsubscribe)
.subscribe(
data => {
some result
},
error => { },
() => {
});
}
someProcedure() {
this.someService.ThirdCall(parametesr)
.takeUntil(this.ngUnsubscribe)
.subscribe(
data => {
some result
},
error => { },
() => {
});
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.