ket
ket

Reputation: 758

Why does WhenAnyValue observable trigger on subscription?

I have the following dummy view model:

public class DummyViewModel : ReactiveObject
{
    internal DummyViewModel()
    {
        ItemChanged.Subscribe(_ => Console.WriteLine());
    }

    public IObservable<string> ItemChanged
    {
        get { return this.WhenAnyValue(x => x.Item).Select(s => s); }
    }

    private string _item;

    public string Item
    {
        get { return _item; }
        set { this.RaiseAndSetIfChanged(ref _item, value); }
    }
}

When I create a new instance of this class, the observable fires immediately on subscription, returning null (nothing is bound to Item). This is causing a problem in my more advanced viewmodels where I have multiple observables that I need to chain together in different ways. I've been using a combination of Skip and StartWith, but it's getting pretty complicated. Can someone advise why this is happening and whether there is a different approach I should consider?

Upvotes: 2

Views: 1601

Answers (1)

Charles Mager
Charles Mager

Reputation: 26213

I guess it's just 'by design'. WhenAny and friends always return the initial value. This makes sense in most cases - for example, if you use ToProperty at the end, and you would usually want your property to have get the initial value.

Obviously I don't know the details of your app, but I've got two reasonably sized apps and can't think of a time I've needed to skip the initial value.

Internally, WhenAny delegates to ObservableForProperty and ObservableForProperty has a skipInitial argument. So you could use that. Or just .Skip(1).

Upvotes: 5

Related Questions