# Attach, detach, and reuse

Let a view listen to a data source while the user can see it, and stop listening when the page leaves. This prevents a long-lived service from keeping old pages alive.

There are two related boundaries. **Attachment** connects the view to the visual tree and its services. **Activation** says the view is currently participating in events, rendering, and animation. A view can become inactive without being discarded.

## Subscribe for the active period

```csharp
using System;
using Xui.Core.Canvas;
using Xui.Core.UI;

// Publish on the UI thread; a background producer must dispatch first.
public sealed class StatusSource
{
    public string Text { get; private set; } = "Waiting for a message";

    public event Action? Changed;
    public void Publish(string text)
    {
        Text = text;
        Changed?.Invoke();
    }
}

public sealed class StatusView(StatusSource source) : View
{
    protected override void OnActivate()
    {
        source.Changed += OnChanged;
        InvalidateRender();
    }

    protected override void OnDeactivate() => source.Changed -= OnChanged;
    private void OnChanged() => InvalidateRender();
    protected override void RenderCore(IContext context)
    {
        context.SetFill(new Color(0x8538CEFF));
        context.SetFont(new Font(18, "Inter"));
        context.TextBaseline = TextBaseline.Middle;
        context.FillText(source.Text, (Frame.X + 16, Frame.Center.Y));
    }
}
```

Create one `StatusSource`, give it to the view, and call `Publish` from the UI thread. The view reads the latest text when it renders; it does not keep a second copy that can get out of sync.

`OnActivate` subscribes and requests an initial render. `OnDeactivate` removes the same named handler. The named method makes unsubscription exact: a newly constructed lambda would not remove a different delegate created earlier.

If the source publishes while the view is inactive, it still stores the latest text. When the view becomes active again, the initial invalidation displays that current value. Reuse does not require replaying every missed message.

## Pick the lifetime that matches the work

Use `OnAttach(ref AttachEventRef)` and `OnDetach(ref DetachEventRef)` for resources tied to membership in the tree. Use `OnActivate` and `OnDeactivate` for work that should pause while dormant: subscriptions, animation, and page-specific background operations.

Attachment walks from parent to child; detachment walks from child to parent. Activation and deactivation follow the same respective directions. Register children through `SetProtectedChild` or a framework collection so those callbacks actually reach them.

Do not manually call lifecycle overrides when navigating. Change the tree through the normal content/navigation APIs. A constructor runs once, whereas a view may attach or activate more than once; keep those repeatable cycles in mind.

## Keep asynchronous work from returning to an old page

The example's source deliberately publishes on the UI thread. If a producer runs on a worker thread, dispatch the update before changing view state. For page-owned asynchronous work, cancel it when the page deactivates and check that it still belongs to the current activation before applying its result. Cancellation alone does not guarantee a completed callback cannot arrive.

A useful test is to navigate to a page, navigate away, publish a status, then return. The old view must not keep processing events after deactivation, and the current view must show the latest status once. Repeat the cycle several times to catch duplicate subscriptions.

Continue with [Animation lifetime and motion preferences](../../animation/lifetime/index.md) for the same ownership rule applied to frames.
