0

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?

5
  • "Is there a better pattern to achieve that?" yes, don't inject side effects into observable streams in the first place. Something like UnlinkFile belongs inside a Subscribe, not inside a Select. If you really must use this anti-pattern, then I guess you're looking for Observable.Create. Feb 3, 2018 at 23:59
  • 3
    I would use Observable.Start(() => File.Delete(fileRef.Path)). Feb 4, 2018 at 3:14
  • @LucasTrzesniewski: In a normal time, I'd agree, but sometimes this doesn't looks to be possible or event desirable. In my case, this class has knowledge about the "filesystem" thing, and provides observables that may or may not modify its state. Provides, not subscribes to them. Consumers of this class do not have interest in that filesystem, therefore they can't just invoke the filesystem side effects in their subscribe (in fact,I don't even have Subscribes, this is handled automatically by the UI code). Feb 4, 2018 at 9:39
  • Second objection: I have other things to do after this side effects. Where could I put them then? At least this observable stream describes what happens and does it in one place, without violating responsibility principles. I agree that SelectMany haven't the semantics in its name to be expected to do side effects, but I don't know if I can really do better. Feb 4, 2018 at 9:42
  • @Enigmativity Is it a 1:1 equivalent of my method, and is it cold? If yes, would you mind posting an answer so I can accept it rather than upvoting the comment? :) Feb 4, 2018 at 9:43

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.