How to Cancel RxJS Requests in Angular with Ngrx

How to Cancel RxJS Requests in Angular with Ngrx
Photo by JJ Ying / Unsplash

when using effects to query an API, a switchMap can help you cancel previous requests - which means that if your user searches for x and while that request is still loading, the user modifies their search - switchMap will cancel the previous request and only honor the last emitted value.

but what do you do if the user cancels their search using a cancel button or removes the text from the searchbar?

there is no request being emitted as a result and your request is left dangling.

takeUntill

we can create a cancel action that takeUntill listens to, and if it is emitted mid-request, the request is canceled.

notice line 7 where it listens to a cancelHydrate action. if that action is dispatched, it will cancel the request in process.

you can use this action on a resetSearch function or when the user input field is given an empty string, resulting in a much cleaner user experience