2

I've created this method in order to create Observable's from events. I'm trying to download a file, and update a progress bar:

private void BuildObservables(WebClient webClient)
{
    Observable.FromEventPattern<AsyncCompletedEventHandler, AsyncCompletedEventArgs>(h => webClient.DownloadFileCompleted += h, h => webClient.DownloadFileCompleted -= h)
        .Select(ep => ep.EventArgs)
        .Subscribe(
            _ =>
            {
                //stuff code
            },
            _ => this.WizardViewModel.PageCompleted()   <<<<< (*) NOT REACHED
        );

    Observable.FromEventPattern<DownloadProgressChangedEventHandler, DownloadProgressChangedEventArgs>(h => webClient.DownloadProgressChanged += h, h => webClient.DownloadProgressChanged -= h)
        .Select(ep => ep.EventArgs)
        .Subscribe(
            a =>
            {
                <<<<< (*) NOT REACHED
                this.progressEdit.Position = a.ProgressPercentage;
                progressEdit.Update();
            }
        );
}

I'm facing up that (*) point marked on source (onCompleted and onNext) are not reached.

Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333

1 Answers1

2
  • Your OnCompleted handler is actually an OnError handler. OnCompleted lambdas don't take an argument, use () => ... instead of _ => ... to hit the correct overload - but this won't help anyway because:

  • Even once corrected, the OnCompleted won't fire. FromEventHandler does not map .NET events to OnCompleted - there is no meaningful conversion. For a complete understanding of why this is, see my answer in How to use Observable.FromEvent instead of FromEventPattern and avoid string literal event names. In your case, the OnNext handler is what you want anyway.

  • The OnNext event certainly fires for me in a simple test app downloading "www.google.com" are you allowing time for the events to fire before the app terminates? Are you calling BuildObservables before calling DownloadXXXAsync - if you don't you may be missing the events? If this doesn't help, can you provide a minimal fully-working repro demonstrating the issue?

Community
  • 1
  • 1
James World
  • 29,019
  • 9
  • 86
  • 120
  • 1
    A `.Take(1)` should cause the `OnCompleted` to fire. – Enigmativity Jan 15 '17 at 11:04
  • That's true. It doesn't change the fact that the underlying .NET event has no equivalent representation of "completing", but it certainly could be useful for cleaning up resources in observable chains when you know you are looking for exactly one event. – James World Jan 15 '17 at 11:27