Morgan Touverey Quilling
Morgan Touverey Quilling

Reputation: 4333

Rx: Wrap simple synchronous calls in cold observables

I often find myself having to transform simple synchronous calls or functions into observable-compatible ones, so I can compose observable streams more easily.

For example, my last one:

public IObservable<Unit> UnlinkFile(FileRef fileRef) {
    try {
        File.Delete(fileRef.Path);

        return Observable.Return(Unit.Default);
    } catch (Exception ex) {
        return Observable.Throw<Unit>(ex);
    }
}

Now I can do:

.SelectMany(_ => filesystem.UnlinkFile(fileRef))

I could use .Do, but the problem with .Do is that it won't throw classic SEH exceptions back into the Observable it is part of.

Is there a better pattern to achieve that? What are our options? Should I better use Observable.Start(), Observable.Create() or something else, to get a cold observable?

Is there another syntax to avoid the above boilerplate?

Upvotes: 0

Views: 245

Answers (1)

Enigmativity
Enigmativity

Reputation: 117029

I would use Observable.Start(() => File.Delete(fileRef.Path)).

You just have to make sure that you have one subscriber at a time to the observable.

Upvotes: 3

Related Questions