reactiveui/ReactiveUI — pull request #503 by paulcbetts (2014-01-23 05:46:17+00:00)
Title: View / ViewModel Activation

Consider the following ViewModel constructor:

```cs
public MyBrokenViewModel()
{
UserError.RegisterHandler(x => {
// NB: Stuff
});
}
```

This is broken because every time we create MyBrokenViewModel, we create another error handler. What Do? What we really want, is for UserError to be subscribed only when the View associated with the ViewModel is *visible*. However, that information isn't available to ViewModels, and even if it was, it's not super obvious. Let's fix it

## How does this work:

Activation allows you, for both Views and ViewModels, to set up *the things that should be* **active** *when the View is visible*. Here's how you do it for ViewModels:

```cs
public class MyWorkingViewModel : ReactiveObject, ISupportsActivation
{
public ViewModelActivator Activator { get; protected set; }

public ActivatingViewModel()
{
Activator = this.WhenActivated(d => {
// d() registers a Disposable to be cleaned up when
// the View is deactivated / removed
d(UserError.RegisterHandler(x => {
// NB: Stuff
}));
});
}
}
```

Here's how it works for Views:

```cs
public class MyWorkingView : UserControl, IViewFor
{
public ActivatingView()
{
this.WhenActivated(d => {
Console.WriteLine("Helloooooo Nurse!")
d(Disposable.Create(() => Console.WriteLine("Goodbye, Cruel World")));
});
}
}
```

Note that calling `WhenActivated` in a View automatically means that the associated ViewModel gets notified for activated / deactivated changes (and in fact, you *must* call `WhenActivated` in the View to get the ViewModel to be notified).