0

The code:

public class AppViewModel : ReactiveObject { public AppViewModel() { Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler) .Do(_ => Score++) .Subscribe(); } private long _score; public long Score { get => _score; set => this.RaiseAndSetIfChanged(ref _score, value); } } 

Is functionally equivalent to:

public class AppViewModel : ReactiveObject { private readonly ObservableAsPropertyHelper<long> _score; public AppViewModel() { _score = Observable .Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler) .ToProperty(this, x => x.Score); } public long Score => _score.Value; } 

Although, in the second case, there's a noticeable delay (of over a second on my machine) before counting starts. What would be the cause of this?

For completeness:

MainWindow.xaml

<reactiveui:ReactiveWindow x:Class="ReactiveDemo.MainWindow" x:TypeArguments="reactivedemo:AppViewModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:reactivedemo="clr-namespace:ReactiveDemo" xmlns:reactiveui="http://reactiveui.net" Title="Rx" Height="450" Width="800" mc:Ignorable="d"> <Viewbox> <Label x:Name="ScoreLabel" ContentStringFormat="D2" FontFamily="Lucida Console" /> </Viewbox> </reactiveui:ReactiveWindow> 

MainWindow.xaml.cs

using ReactiveUI; using System.Reactive.Disposables; namespace ReactiveDemo { public partial class MainWindow : ReactiveWindow<AppViewModel> { public MainWindow() { InitializeComponent(); ViewModel = new AppViewModel(); this.WhenActivated(disposableRegistration => { this.OneWayBind(ViewModel, viewModel => viewModel.Score, view => view.ScoreLabel.Content) .DisposeWith(disposableRegistration); }); } } } 

1 Answer 1

1

The ToProperty overload that you are using has a reflection cost. Try ToProperty(this, nameof(Score)). There may still be a performance hit as the ToProperty does a bit more than the functional equivalent you've posted.

Sign up to request clarification or add additional context in comments.

4 Comments

Would argue it's more the timer is requested to start 1 second with the first parameter.
@Rodney Thanks for the tip, no improvement though. Yeah I know about their differences, I went over the code base. Still, a base line of a second seems like a lot. We're not even doing anything in the pipe yet.
@Glenn How do you mean? Both snippets declare the timer in exactly the same way, yet the first starts counting as soon as the view is shown.
Ah it just hit me. In the first snippet the score already gets incremented when the observable ticks zero. Thanks guys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.