2

I have a button that alternates between play/pause. Rather than flip-flopping a boolean, I want to see if there is a good solution using reactive extensions. Here is a rough estimate of what I was thinking.

var whenPlayClicked = Observable.FromEventPattern<EventArgs>(_playPauseButton, "Click")
    .Take(1)
    .Skip(1)
    .Repeat();

var whenPauseclicked = Observable.FromEventPattern<EventArgs>(_playPauseButton, "Click")
    .Skip(1)
    .Take(1)
    .Repeat();

1 Answers1

5

Rx doesn't provide any native operators for simply toggling a boolean value; however, you can write a pretty elegant Scan query that avoids closures.

void UserControl_Loaded(object sender, RoutedEventArgs e)
{
  Observable.FromEventPattern(_playPauseButton, "Click")
            .Scan(false, (play, _) => !play)
            .Subscribe(play => { if (play) Play(); else Pause(); });
}

private void Play()
{
  _playPauseButton.Content = "Pause";
}

private void Pause()
{
  _playPauseButton.Content = "Play";
}
Dave Sexton
  • 2,562
  • 1
  • 17
  • 26
  • 1
    Thanks for the answer. I've never seen the `Scan` extension method before. I like that this option doesn't require an extra class variable. – Nathan Phetteplace Sep 30 '14 at 12:18