How to use Observable.FromEvent with static events?

巧了我就是萌 提交于 2019-12-10 11:08:54

问题


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:


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.



来源:https://stackoverflow.com/questions/3274815/how-to-use-observable-fromevent-with-static-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!