Skip to content

OAPH cannot be created outside of constructor (i.e. in WhenActivated clause) #75

@sdijoseph

Description

@sdijoseph

Is your feature request related to a problem? Please describe.

It currently doesn't seem possible to subscribe to a OAPH outside of the constructor of the view model. This is desirable when you want to unsubscribe to a OAPH when the view model is deactivated. For example:

using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
using ReactiveUI.SourceGenerators;

namespace MyNameSpace;

public partial class TestViewModel : ReactiveObject, IActivatableViewModel
{
    public ViewModelActivator Activator { get; } = new();

    [ObservableAsProperty] private bool _test;

    public TestViewModel()
    {
        this.WhenActivated(disposables =>
        {
            _testHelper = Observable.Return(true)
                .ToProperty(this, x => x.Test)
                .DisposeWith(disposables);
        });
    }
}

Right now, this does not compile since _testHelper is defined as readonly:

// <auto-generated/>
#pragma warning disable
#nullable enable
namespace MyNameSpace
{
    /// <inheritdoc/>
    partial class TestViewModel
    {
        /// <inheritdoc cref="_testHelper"/>
        [global::System.CodeDom.Compiler.GeneratedCode("ReactiveUI.SourceGenerators.ObservableAsPropertyGenerator", "1.1.0.0")]
        private readonly ReactiveUI.ObservableAsPropertyHelper<bool> _testHelper;
        /// <inheritdoc cref="_test"/>
        [global::System.CodeDom.Compiler.GeneratedCode("ReactiveUI.SourceGenerators.ObservableAsPropertyGenerator", "1.1.0.0")]
        [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
        public bool Test { get => _test = (_testHelper?.Value ?? _test); }
    }
}

Describe the solution you'd like

I would like to be able to subscribe to OAPH within a WhenActivated clause, so that I can clean-up the subscription on view model deactivation.

Describe alternatives you've considered

Describe suggestions on how to achieve the feature

It seems like a solution that should work is to define any ObservableAsPropertyHelper<T> as ObservableAsPropertyHelper<T>?, and then remove the readonly modifier. I have not tested this myself yet, as I wanted to make sure there wasn't already a way of dealing with this scenario that I've missed.

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions