How to get IObservable back from Web API

I have a simple web API that returns Iobservable. I use HttpClient to get an Observable so that I can subscribe to it. My problem is that the returned Iobservable on subscription sends an "empty" result.

SERVER

public IObservable<DataItem> GetDataItems() { return Observable.Generate(0, i => i < 10, i => i + 1, i => new DataItem { Id = i, Name = String.Format("Storage{0}",i) }); } 

CUSTOMER

 public IObservable<DataItem> GetDataItems() { using (HttpClient apiClient = new HttpClient()) { apiClient.BaseAddress = new Uri("http://localhost:9001"); apiClient.DefaultRequestHeaders.Add("x-user-authentication", "xxxxxx"); return apiClient .GetAsync("api/xxxx/yyyy").Result.Content .ReadAsAsync<DataItem>().ToObservable(); } } var source = GetDataItems(); List<DataItem> items = new List<DataItem>(); IDisposable consoleSubscription = source.Subscribe( x => Console.WriteLine("{0}:{1}", x.Id, x.Name), ex => Console.WriteLine("OnError : {0} ", ex.Message), () => Console.WriteLine("Encountered End of Stream") ); consoleSubscription.Dispose(); 

My problem: I do not receive any data from the server. I get an "empty" observable. I wrote a unit test against my controller and it returns data.

Any suggestions please help. It is impossible to understand where I am mistaken. There are no errors on the server or client.

+6
source share
1 answer

You are a bit ambitious, expecting the IObservable<T> be automatically transmitted over the cable. I am afraid that the WebAPI will not do this for you.

What you see is the result of the default json serializer outputting the IObservable<T> properties - and they are not there, so you get empty curly braces.

Your unit test works because everything in memory - serialization / deserialization does not occur.

There are ways to use the HttpResponseMessage StreamContent property to stream results that you could translate to / from IObservable<T> , but this is not really an idiomatic WebApi. Async support for WebApi is really aimed at asynchronously processing requests with responses of individual elements on the server, rather than returning continuous streams of events.

In the end, I believe that WebApi (at least at the time of writing) is the wrong technology choice here. You look much better at SignalR , which is designed for such a scenario and is included in the current version of ASP. NETWORK. It supports both javascript and .NET, and you can easily switch to IObservable<T> . Some people have already looked at this, for example in this example code for sports games .

Some middleware for messaging, such as my-Channels Nirvana (Edit: since Terracotta bought it and is packaged in Universal Messaging Some, sample code is available in their documentation.) And CEP solutions like SQL Server StreamInsight also have built-in IObservable support.

+17
source

Source: https://habr.com/ru/post/958896/


All Articles