runceel / ReactiveProperty

ReactiveProperty provides MVVM and asynchronous support features under Reactive Extensions. Target frameworks are .NET 6+, .NET Framework 4.7.2 and .NET Standard 2.0.
MIT License
896 stars 100 forks source link

Why does `DisposePreviousValue` require `ToReadOnlyReactivePropertySlim` #396

Closed gmkado closed 1 year ago

gmkado commented 1 year ago

I was trying to use DisposePreviousValue introduced in #167 and found that I needed to add the line ToReadOnlyReactivePropertySlim, even though I wasn't using the resulting reactive property. Why is this?

    public static void Main()
    {
        var source = new Subject<string>();
        source.Select(x => new Test(x))
            .DisposePreviousValue();
            //.ToReadOnlyReactivePropertySlim();  // <-- with this comment, dispose is no longer called

        source.OnNext("first"); 
        source.OnNext("second");
        source.OnNext("third");

    }

    public class Test:IDisposable{
        private readonly string _x;
        public Test(string x){_x = x;}
        public void Dispose()=> Console.WriteLine(_x);
    }
runceel commented 1 year ago

You need calling Subscribe method to run the LINQ sequence.

using Reactive.Bindings.Extensions;
using System.Reactive.Linq;
using System.Reactive.Subjects;

var source = new Subject<string>();
source.Select(x => new Test(x))
    .DisposePreviousValue()
    .Subscribe(); // here

source.OnNext("first");
source.OnNext("second");
source.OnNext("third");

public class Test : IDisposable
{
    private readonly string _x;
    public Test(string x) { _x = x; }
    public void Dispose() => Console.WriteLine(_x);
}

Why ToReadOnlyReactivePropertySlim is required. Because Subscribe method is called in ToReadOnlyReactivePropertySlim.

gmkado commented 1 year ago

Ah okay makes sense. Thank you!