Rx - can/should I replace .NET events with Observables?

前端 未结 5 1725
挽巷
挽巷 2020-12-12 18:13

Given the benefits of composable events as offered by the Reactive Extensions (Rx) framework, I\'m wondering whether my classes should stop pushing .NET events, and instead

5条回答
  •  暖寄归人
    2020-12-12 18:42

    For #2, the most straightforward way is via a Subject:

    Subject _Progress;
    IObservable Progress {
        get { return _Progress; }
    }
    
    private void setProgress(int new_value) {
        _Progress.OnNext(new_value);
    }
    
    private void wereDoneWithWorking() {
        _Progress.OnCompleted();
    }
    
    private void somethingBadHappened(Exception ex) {
        _Progress.OnError(ex);
    }
    

    With this, now your "Progress" can not only notify when the progress has changed, but when the operation has completed, and whether it was successful. Keep in mind though, that once an IObservable has completed either via OnCompleted or OnError, it's "dead" - you can't post anything further to it.

提交回复
热议问题