views:

88

answers:

1

I am trying to use Reactive Extensions to write code to handle an asynchronous call where both the initiating method and the completed event are static. I can't use

var languageSetsLoaded = Observable
  .FromEvent<LoadLanguageSetsCompletedEventArgs>(
    LanguageManager, "LanguageSetsLoaded")

as LanguageManager is a static class rather than an instance, so I tried

var languageSetsLoaded = Observable
  .FromEvent<LoadLanguageSetsCompletedEventArgs>(
    h => LanguageManager.LanguageSetsLoaded += h,
    h => LanguageManager.LanguageSetsLoaded -= h )

but that gives a syntax error "Cannot convert lambda expression to type 'object' because it is not a delegate type". The event is declared thus

public delegate void LoadLanguageSetsCompletedHandler(LoadLanguageSetsCompletedEventArgs e);
public static event LoadLanguageSetsCompletedHandler LanguageSetsLoaded = delegate { };

so I think it is a delegate type and perhaps the fact that it is static is producing a misleading error description.

Is their some way to do this or am I just going to have to stick to non-reactive code like this?

private void ChangeLanguage(string languageCode)
{
  LanguageManager.LanguageSetsLoaded += OnLanguageSetsLoaded;
  LanguageManager.LoadLanguageSets(languageCode, BaseApp.InTranslationMode);
}

private void OnLanguageSetsLoaded(LoadLanguageSetsCompletedEventArgs e)
{
  LanguageManager.LanguageSetsLoaded -= OnLanguageSetsLoaded;
  OnPropertyChanged("DummyLanguageResource");
}
+1  A: 

I think the problem is your delegate type of your event. Try changing it to:

public static event EventHandler<LoadLanguageSetsCompletedEventArgs> 
    LanguageSetsLoaded = delegate { };

If you look at the signature of Observable.FromEvent that you're trying to use, it looks like this:

public static IObservable<IEvent<TEventArgs>> FromEvent<TEventArgs>(
    Action<EventHandler<TEventArgs>> addHandler,
    Action<EventHandler<TEventArgs>> removeHandler
)
where TEventArgs : EventArgs

Alternatively you could use the overload which has three arguments, the first one being a conversion handler - but I think you'd be better off just changing the event signature if at all possible.

Jon Skeet