What are the distinctions between the various WhenAny methods in Reactive UI

后端 未结 1 1228
耶瑟儿~
耶瑟儿~ 2020-12-14 16:00

There are several extension methods in Reactive UI for getting observables for property changes.

I think I understand WhenAny and WhenAnyValue

1条回答
  •  [愿得一人]
    2020-12-14 16:53

    I think I understand WhenAny and WhenAnyValue.

    Let me demonstrate via code:

    // These two statements are 100% identical, but the latter looks nicer.
    this.WhenAny(x => x.Foo.Bar, x => x.Value)
    
    this.WhenAnyValue(x => x.Foo.Bar);
    

    What about WhenAnyDynamic, WhenAnyObservable, and ObservableForProperty?

    WhenAnyDynamic is like WhenAny but when the things you want to observe aren't constants - you probably won't need it, but RxUI internals does.

    WhenAnyObservable lets you get an Observable, but not have to worry about objects changing behind your back. For example

    this.SomeChildViewModel.MyCoolCommand
        .Subscribe(x => Console.WriteLine("Clicked!"));
    
    // Later...
    this.SomeChildViewModel = new SomeChildViewModel();
    
    // (Hey, why doesn't my Clicked! handler show up anymore! I'm still subscribed
    // to the old object but it's super not obvious that's what happened)
    

    Versus

    this.WhenAnyObservable(x => x.MyCoolCommand).
        .Subscribe(x => Console.WriteLine("Clicked!"));
    
    // Later...
    this.SomeChildViewModel = new SomeChildViewModel();
    
    // Cool, everything still works.
    

    WhenAnyObservable is super useful in the View to Subscribe to Commands.

    ObservableForProperty is like WhenAny but doesn't fire when initially subscribed to. You probably should ignore it, it's really just a building block for WhenAny that is around for compatibility reasons.

    0 讨论(0)
提交回复
热议问题