How to cancel an asynchronous method called using Rx

I want to know how to cancel / stop the asynchronous method called using reactive extensions using TakeUntil.

So, I want to be able to cancel \ stop the following method:

this.booksService.Search(searchText)
                 .ObserveOnDispatcher()
                 .Subscribe(results =>
                 {
                    this.books.Clear();
                    this.books.AddRange(results);
                 });
+3
source share
3 answers

The return from Subscribe()is IDisposablewhen you set a value, for example:

var searchSub = this.booksService
                    .Search(searchText) ...
                    .Subscribe( ... );
// do something else
searchSub.Dispose();

subscription terminated. Does this actually mean stopping the search for books? It depends on the implementation. If w / is done Observable.Create, then it is quite possible to get this behavior.

+2
source

booksService, . Search , IObservable. , OnNext IObservable. Search , .

0

My recommendation is to change the search method to an asynchronous call that takes a CancellationToken value as the second argument. You can then convert this to an observable sequence through Observable.ToAsync. A utility call on this observable will trigger the cancellation of the CancellationToken. This makes it easy to transfer the token to asynchronous web calls, etc.

public Task Search(string searchText, CancellationToken cancel)
{
    // Pass the token on to the async webclient request etc.
}

var searchSub = Observable.ToAsync(c => this.booksService.Search(searchText, c))
                .Subscribe( ... );
// do something else
searchSub.Dispose();
0
source

All Articles