I’m kinda new to Observables so I’m just looking for an example that will set me in the right direction (tutorial maybe?). So here it is – I want to create async Observable and thow an Exception from it. Here is my example:
protected IObservable<Tuple<DataPart1, DataPart2>> LoadAllDataFunc(string FileName)
{
return Observable.Start<Tuple<DataPart1, DataPart2>>(() =>
{
ConfigReaderWriter readerWriter = new ConfigReaderWriter();
try
{
readerWriter.UnpackFile(fileName, out DataPart1, out DataPart2);
return Tuple.Create(DataPart1, DataPart2);
}
catch (Exception exp_gen)
{
Observable.Throw<Exception>(exp_gen);
return null;
}
});
}
The problem is that I don’t think I’m not throwing Exception correctly. For example – any Subscriber:
internal IObservable<DataPart2> GetProject()
{
if (this.GlobalDataPart2 != null)
return Observable.Return(GlobalDataPart2);
IObservable<Project> receivedData = null;
var loadAll = LoadAllDataFunc(this.GlobalFileName).Subscribe(
data => { receivedData = Observable.Return(data.Item1); },
(ex) => { Observable.Throw<Exception>(ex); }
);
return receivedData;
}
will not receive Exception from LoadAllDataFunc ? Even if exception occurred the Subscriber will receive null.
So – what is correct way to throw exception from Observable?
Just to make it crystal clear what Observable.Throw does: it returns an observable sequence (of the specified element type) whose sole role it is to tell all of its observers about an exception by calling their OnError method:
The code above will print Oops! twice.
As Gideon mentioned, operators like Start will propagate user exceptions to the OnError channel. If you use Observable.Create though, talk to the observer directly about the error case:
In fact, the code shown above is pretty close to what Start does anyway. (The one difference has to do with the use of an AsyncSubject to cache the operation’s result.)