Cancel Obsolete Http Requests in Rx.NET with the Switch Operator

Georg Dangl by Georg Dangl in DotNet Thursday, January 30, 2020

Thursday, January 30, 2020

Posted in Rx.NET

Using Observables in Rx.NET is a super fun and efficient way to organize data flows in your applications. While it's widely used for front end development - it's basically a core part of Angular - it's actually a great library to use in any projects where you're using loosely coupled services and state management.

One of these use cases is having a filtered list. Imagine you've got a small app that shows you some table, along with a single text field for filtering. Imagine also that this list is fed from some asynchronous source, so it's not an in memory filter operation but maybe the response from a Http call.

Now, when you start typing in this box, what should happen? In the simplest case, without delays or checks, every letter typed in that filter box sends a Http request. That's probably a bit of an unoptimized approach, but it should work. This could look something like the following:

What's actually happening is that you're creating a stream of events in your code. Whenever you change the url, you're sending a request. When that request finishes, you're updating the list. The problem now comes when the requests don't come in the order they've been sent. Your user might have typed pizza, deleted that and then again typed pasta. If the first request, for really any reason, was delayed, you might have the situation where you're sowing pizza results to pasta guys!

To resolve this, you want to track which requests have been sent and discard all but the latest one. In rxjs, you'd be using the switchMap operator. In Rx.NET, it's simply called Switch and expects you to either provide a Task or another IObservable:

What's happening here is that only the latest call will come through. So when you've got more than one request running at the same time, you're never again getting stale data.

If you want to dive deeper into this, you can take a look at the source code for LightQuery, which uses this approach in conjunction with CancellationTokens. I'd also like to thank Brandon for providing a great answer at StackOverflow, which really goes into detail!

Hope you're going to have fun with Rx.NET!

Share this post

comments powered by Disqus

About me

Hi, my name's George! I love coding and blogging about it. I focus on all things around .Net, Web Development and DevOps.


Need a consultant for BIM, GAEB or Software Development?

Contact me at [email protected], +49 (173) 56 45 689 or visit my professional page!

// Just 💗 Coding

Social Links