Reputation: 2631
I wrap a http call to a new Observable, but I cannot detect if the subscription is cancelled:
constructor( @Inject(Http) private http: Http) {
}
...
const observable = Observable.create((observer: Observer<any>) => {
this.http.post(url, body)
.subscribe((p) => {
observer.next(p.json());
observer.complete();
}, (err) => {
observer.error(err);
observer.complete();
});
});
const subscription = observable.subscribe((r) => { alert("result : "+r); }, (err) => { alert("error occured");}
subscription.unsubscribe(); // if user cancels the request
How can I detect in Observable.create(...)
if the user cancels the subscription? I would like to cancel the http post request when the outer Observable is cancelled.
Upvotes: 1
Views: 1690
Reputation: 4788
You can manually create unsubscribe
function like:
constructor(public http: HttpClient) {
let url = 'google.kz';
const observable = Observable.create((observer: Observer<any>) => {
let cancel: Subscription = this.http.post(url, {})
.subscribe((p) => {
observer.next(p);
observer.complete();
}, (err) => {
observer.error(err);
observer.complete();
});
// Provide a way of canceling and disposing the internal observables
return function unsubscribe() {
cancel.unsubscribe();
};
});
let unsc = observable.subscribe(data => {
console.log(data);
})
console.log('unsubscribe', unsc);
unsc.unsubscribe();
}
So, when you call unsubscribe()
function of outer observable, inner observables unsubscribes too depending how it realized
Upvotes: 3