How to convert a method that takes an OnError and OnCompleted into an Observable
There is probably a really easy answer to this but my brain just isn't working.
I have a method I need to call in a framework that is not Observable aware, that has the following pattern.
client.GetAsync<TResult>(
string resource,
Action<Exception> onError,
Action<TResult> onCompleted);
I need to convert this into a synchronous action that waits for 开发者_如何学Gothe result. I figured Rx would help me so I tried
var observable = Observable.Create<XElement>(
observer => () => client.GetAsync<XElement>(
"resource1",
observer.OnError,
observer.OnNext);
var result = observable.First();
But this here but this just deadlocks, I tried making it ObserveOn new thread and SubscribeOn new thread. But it still deadlocks, am I even on the right track?
You're on the right track, with a small adjustment.:
var observable = Observable.Create<XElement>(
observer =>
{
client.GetAsync<XElement>(
"resource1",
observer.OnError,
x =>
{
observer.OnNext(x);
observer.OnCompleted();
});
return () => {};
});
Just as a comment, using RX to make synchronous stuff from asynchronous is kinda "goes against the grain". Normally, RX is used to make asynchronous from synchronous or make asynchronous easier.
精彩评论