Chip
Chip

Reputation: 1559

How do I make an asynchronous HTTP request with RxNET?

Currently I'm using await inside an Observable.Create(). ExecuteRequestAsync is a wrapper class to call HttpClient.GetAsync Method (String)

    public IObservable<IList<ExampleResponseModel>> ListExamplesRx()
    {
        return Observable.Create<IList<ExampleResponseModel>>(
            o =>
            {
                try
                {
                    var url = string.Format(Routes.Examples.List);
                    IList<ExampleResponseModel> exampleResponse = await ExecuteRequestAsync<IList<ExampleResponseModel>>(url, HttpMethod.Get);
                    o.OnNext(exampleResponse);
                    o.OnCompleted();
                }
                catch (Exception e)
                {
                    o.OnError(e);
                }
                return Disposable.Empty;
            }
        );
    }

Is this the best practice? Is there a more appropriate rx solution?

Upvotes: 2

Views: 1281

Answers (1)

Richard Szalay
Richard Szalay

Reputation: 84784

Task<T>.ToObservable() does what you're looking for:

public IObservable<IList<ExampleResponseModel>> ListExamplesRx()
{
    var url = string.Format(Routes.Examples.List);
    return ExecuteRequestAsync<IList<ExampleResponseModel>>(url, HttpMethod.Get)
        .ToObservable();
}

If you want a cold observable (ie. deferred execution) you can wrap the above in Observable.Defer.

If you need to support cancellation, see How to create IObservable from Task such that unsubscribing cancels the task?

Upvotes: 6

Related Questions