Skip to content

Add IComposer.MutableStateOf extension and implicit MutableState<T> → T - #229

Merged
jonathanpeppers merged 2 commits into
mainfrom
jonathanpeppers/mutable-state-of-ergonomics
Jun 10, 2026
Merged

jonathanpeppers merged 2 commits into
mainfrom
jonathanpeppers/mutable-state-of-ergonomics

Conversation

@jonathanpeppers

Copy link
Copy Markdown
Owner

Brainstorm suggestion #2 — MutableStateOf ergonomics. Bring the C# call site closer to Kotlin's var count by remember { mutableStateOf(0) }.

Before / after

Kotlin:

var count by remember { mutableStateOf(0) }
Column {
    Text("Count: $count")
    Button(onClick = { count++ }) { Text("Tap") }
    if (count > 0) Text("non-zero")
}

C# before:

var count = c.Remember(() => new MutableNumberState<int>(0));
return new Column {
    new Text($"Count: {count}"),
    new Button(onClick: () => count++) { new Text("Tap") },
    count.Value > 0
        ? new Text("non-zero")
        : null,
};

C# after:

var count = c.MutableStateOf(0);
return new Column {
    new Text($"Count: {count}"),
    new Button(onClick: () => count++) { new Text("Tap") },
    count > 0
        ? new Text("non-zero")
        : null,
};

Three sub-changes (all landed)

1. composer.MutableStateOf(initial) extension family

Single name, five overloads in ComposeExtensions.State.cs:

  • MutableStateOf<T>(this IComposer, T) — generic catch-all → MutableState<T>
  • MutableStateOf(this IComposer, int) → MutableNumberState<int>
  • MutableStateOf(this IComposer, long) → MutableNumberState<long>
  • MutableStateOf(this IComposer, float) → MutableNumberState<float>
  • MutableStateOf(this IComposer, double) → MutableNumberState<double>

C# overload resolution (§11.6.4.3) prefers the non-generic numeric overloads for literal int/long/float/double values, so c.MutableStateOf(0) returns MutableNumberState<int> and gets ++/-- for free, while c.MutableStateOf("Ada") falls through to the generic MutableState<string>. Each overload forwards [CallerLineNumber]/[CallerFilePath] to Remember so call sites own a stable slot key.

Call site Picked overload Returned type ++
c.MutableStateOf(0) int MutableNumberState<int> ✓
c.MutableStateOf(1000L) long MutableNumberState<long> ✓
c.MutableStateOf(0.5f) float MutableNumberState<float> ✓
c.MutableStateOf(Math.PI) double MutableNumberState<double> ✓
c.MutableStateOf("Ada") generic MutableState<string> n/a
c.MutableStateOf(false) generic MutableState<bool> n/a
c.MutableStateOf<long?>(null) generic (explicit T) MutableState<long?> n/a

2. Implicit MutableState<T> → T

public static implicit operator T(MutableState<T> state)
{
    ArgumentNullException.ThrowIfNull(state);
    return state.Value;
}

if (count > 0), int x = state;, state + 5 all light up. $"Count: {count}" interpolation keeps calling ToString() (interpolation boxes args as object, which doesn't trigger user-defined conversions), so existing formatting is preserved. Inherited by MutableNumberState<T> per the C# spec.

HelloCounterDemo.cs now runtime-exercises the conversion via a count > 0 ? new Text(...) : null line.

3. Fold the primitive fast path into MutableState<T>

Kind probe, CreateState (picks IMutableIntState/IMutableLongState/IMutableFloatState), specialised Value getter/setter, and re-probe on SetUnderlyingState for RememberSaveable round-trip — all moved from MutableNumberState<T> into the base. Now every new MutableState<int>(0) (and the new c.MutableStateOf(0)) benefits from the primitive backing. MutableNumberState<T> stays as a thin 4-line subclass that only adds operator ++/-- (which still requires T : INumber<T>).

This was feasible because the fast-path machinery only checks typeof(T) — it never needs INumber<T>. Only ++/-- does.

Migration

Swept 119 call sites across 79 files in samples/Jetchat, samples/JetNews, samples/Reply, the gallery demos, and the facade internals from c.Remember(() => new Mutable[Number]State<T>(x)) to c.MutableStateOf(x). Sites needing explicit T for null literals (c.MutableStateOf<long?>(null)) handled by hand. RememberSaveable(() => new MutableNumberState<int>(0)) left as-is — RememberSaveable is the explicit path for bundle persistence and doesn't fit the new family.

A handful of stale using AndroidX.Compose.UI.Text.Input; directives (no longer needed since MutableState<TextFieldValue> isn't named at call sites anymore) were trimmed via dotnet format style --diagnostics IDE0005.

Public API delta

PublicAPI.Unshipped.txt:

  • Add (6 lines): five MutableStateOf overloads + one MutableState<T>.implicit operator T.
  • Remove (2 lines): override AndroidX.Compose.MutableNumberState<T>.Value.get/set — the getter/setter slot now lives on the base type. Binary compatibility preserved (callers continue to resolve through the inherited virtual).

Verification

  • dotnet build src/Microsoft.AndroidX.Compose — clean (RS0016/RS0017 included)
  • dotnet build src/Microsoft.AndroidX.Compose.Gallery — clean
  • dotnet build samples/Jetchat, samples/JetNews, samples/Reply — all clean
  • dotnet test src/Microsoft.AndroidX.Compose.SourceGenerators.Tests — 130/130 pass

No -t:Run per request — implicit-conversion exercise lives in HelloCounterDemo for on-device follow-up.

Possible follow-ups

  • MutableStateOf<T>(initial, SnapshotMutationPolicy policy) — Kotlin power-user shape, file a separate issue if requested.
  • [Obsolete("Use MutableState<T> directly", error: false)] on MutableNumberState<T> — could be considered now that the fast path lives on the base, but the subclass still uniquely provides ++/-- so kept un-marked. Worth a separate discussion.

Coordination note

Two other parallel sessions are touching MaterialTheme.cs / Modifier.cs call sites. Merge conflicts on PublicAPI.Unshipped.txt at review time are expected and mechanical (re-sort).

Co-authored-by: Copilot [email protected]

Brainstorm suggestion #2 -- bring C# call sites closer to Kotlin's
`var count by remember { mutableStateOf(0) }`.

Three sub-changes, all landed:

1. Add a single `composer.MutableStateOf(initial)` extension family with
   one generic catch-all overload and four non-generic numeric specialisations
   for int/long/float/double. C# overload resolution prefers the non-generic
   numeric overloads for literal int/long/float/double values, so
   `c.MutableStateOf(0)` returns `MutableNumberState<int>` and gets `++/--`
   for free, while `c.MutableStateOf("Ada")` falls through to the generic
   `MutableState<string>`. Forwards `[CallerLineNumber]`/`[CallerFilePath]`
   to `Remember` so each call site owns a stable slot key.

2. Implicit conversion `MutableState<T> -> T` so reads like `if (count > 0)`
   and `int x = state;` work without `.Value`. String interpolation
   `$"Count: {count}"` keeps calling `ToString()` (interpolation boxes args
   as `object`, which doesn't trigger user-defined conversions), so existing
   formatting behavior is preserved.

3. Fold the primitive fast path (Kind probe, CreateState picking the right
   `IMutableIntState`/`IMutableLongState`/`IMutableFloatState`, specialised
   `Value` getter/setter, re-probe on `SetUnderlyingState` for
   `RememberSaveable`) from `MutableNumberState<T>` into `MutableState<T>`
   itself. Now every `new MutableState<int>(0)` (and the new
   `c.MutableStateOf(0)`) benefits from the primitive backing.
   `MutableNumberState<T>` stays as a thin 4-line subclass that only adds
   `operator ++/--` (which still requires `T : INumber<T>`).

Migration: swept 119 call sites across 79 files in `samples/Jetchat`,
`samples/JetNews`, `samples/Reply`, the gallery demos, and the facade
internals from `c.Remember(() => new Mutable[Number]State<T>(x))` to
`c.MutableStateOf(x)` (or `c.MutableStateOf<T>(x)` for null/default
literals that need explicit T).

HelloCounterDemo now also runtime-exercises sub-change 2 via a
`count > 0 ? new Text(...) : null` line.

Verification:
- `dotnet build src/Microsoft.AndroidX.Compose` -- clean (RS0016/RS0017 included)
- `dotnet build src/Microsoft.AndroidX.Compose.Gallery` -- clean
- `dotnet build samples/{Jetchat,JetNews,Reply}` -- all clean
- `dotnet test src/Microsoft.AndroidX.Compose.SourceGenerators.Tests` -- 130/130 pass

Public API delta (Unshipped.txt):
- ADD: 5 `MutableStateOf` overloads + 1 `MutableState<T>` implicit operator
- REMOVE: 2 lines for the old `MutableNumberState<T>.Value` overrides
  (the getter/setter slot now lives on the base type)

Co-authored-by: Copilot <[email protected]>
@jonathanpeppers jonathanpeppers changed the title Add IComposer.MutableStateOf extension and implicit MutableState&lt;T&gt; → T Add IComposer.MutableStateOf extension and implicit MutableState<T> → T Jun 10, 2026
@jonathanpeppers
jonathanpeppers marked this pull request as ready for review June 10, 2026 01:04
Copilot AI review requested due to automatic review settings June 10, 2026 01:04
…le-state-of-ergonomics

# Conflicts:
#	samples/Jetchat/Profile.cs

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR delivers three cohesive improvements to MutableState<T> ergonomics, bringing C# call sites closer to Kotlin's by remember { mutableStateOf(0) } pattern. It adds a composer.MutableStateOf(initial) extension family (five overloads leveraging C# overload resolution), introduces an implicit MutableState<T> → T conversion operator, and folds the primitive fast-path machinery (IMutableIntState/IMutableLongState/IMutableFloatState dispatch) from MutableNumberState<T> into the MutableState<T> base class. The PR then sweeps 79 files across the gallery, facade internals, and all three sample apps to adopt the new API.

Changes:

  • New MutableStateOf extension methods on IComposer (generic + four numeric overloads) and implicit operator T on MutableState<T>, with full XML docs and PublicAPI.Unshipped.txt entries.
  • Primitive fast-path logic (Kind enum, CreateState, ProbeKind, specialized Value getter/setter) moved from MutableNumberState<T> to MutableState<T>; MutableNumberState<T> reduced to a 4-line subclass providing only ++/-- operators.
  • Comprehensive call-site migration from c.Remember(() => new Mutable[Number]State<T>(x)) to c.MutableStateOf(x) across gallery demos and sample apps, plus stale using cleanup.

Reviewed changes

Copilot reviewed 85 out of 85 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/Microsoft.AndroidX.Compose/MutableState.cs Absorbs Kind/CreateState/ProbeKind/fast-path Value from MutableNumberState; adds implicit operator T with ThrowIfNull; expanded XML docs
src/Microsoft.AndroidX.Compose/MutableNumberState.cs Reduced to thin subclass: single ctor delegating to base, ++/-- operators only; drops Unsafe/Runtime imports
src/Microsoft.AndroidX.Compose/ComposeExtensions.State.cs Five MutableStateOf overloads (generic + int/long/float/double) forwarding to Remember with [CallerLineNumber]/[CallerFilePath]
src/Microsoft.AndroidX.Compose/PublicAPI.Unshipped.txt Adds 6 entries (5 overloads + implicit operator); removes 2 MutableNumberState<T>.Value override entries
README.md Updates the Kotlin-vs-C# comparison table to show c.MutableStateOf(0) and implicit conversion
src/Microsoft.AndroidX.Compose.Gallery/Demos/Buttons/HelloCounterDemo.cs Migrated + exercises count > 0 implicit conversion at runtime
samples/Jetchat/MainActivity.cs Migrated; removes stale using AndroidX.Compose.UI.Text.Input
72 other gallery/sample files Mechanical migration from c.Remember(() => new Mutable[Number]State<T>(x)) to c.MutableStateOf(x)

@jonathanpeppers
jonathanpeppers merged commit 197d608 into main Jun 10, 2026
1 check passed
@jonathanpeppers
jonathanpeppers deleted the jonathanpeppers/mutable-state-of-ergonomics branch June 10, 2026 01:15
jonathanpeppers added a commit that referenced this pull request Jun 10, 2026
After [#221](../pull/221) (implicit `long → Color` conversion) and [#222](../pull/222) (theme reads off composer), the `*Argb` suffix on color properties is vestigial — callers can pass `scheme.OnSurface` (a `long`) straight to a `Color?` property and the implicit conversion does the rest. The five hand-written facades that still exposed `long? *Argb` are renamed here to match the shape the source-generated `Text` facade already uses (`public Color? Color`).

### Renames

| File | Before | After |
|------|--------|-------|
| `Icon.cs` | `long? TintArgb` | `Color? Tint` |
| `HorizontalDivider.cs` | `long? ColorArgb` | `Color? Color` |
| `VerticalDivider.cs` | `long? ColorArgb` | `Color? Color` |
| `CircularProgressIndicator.cs` | `long? ColorArgb`, `long? TrackColorArgb` | `Color? Color`, `Color? TrackColor` |
| `LinearProgressIndicator.cs` | `long? ColorArgb`, `long? TrackColorArgb` | `Color? Color`, `Color? TrackColor` |

The render bodies still call the bound `DividerKt` / `ProgressIndicatorKt` / `IconKt` bindings (and the `IconPainter` bridge) with a `long` color slot; the new properties are converted via `Color is { } c ? c : 0L`.

### No `[Obsolete]` aliases

Same rationale as [#221](../pull/221), [#223](../pull/223), [#225](../pull/225), [#226](../pull/226), [#229](../pull/229): every removed entry was in `PublicAPI.Unshipped.txt`, never `Shipped.txt`, so a clean break is acceptable pre-1.0. Verified — only `Color.FromArgb(...)` factories remain (intentional, those aren't being renamed).

### Sweep

19 callsite renames across two samples; JetNews and the Gallery had no references.

| Sample | File | Hits |
|--------|------|------|
| Jetchat | `Conversation.cs` | 5 |
| Jetchat | `Profile.cs` | 4 |
| Jetchat | `RecordButton.cs` | 2 |
| Jetchat | `JetchatIcon.cs` | 2 |
| Jetchat | `JetchatDrawer.cs` | 1 |
| Reply | `EmailDetailAppBar.cs` | 1 |
| Reply | `ReplyEmailListItem.cs` | 1 |
| Reply | `ReplyEmailThreadItem.cs` | 1 |
| Reply | `ReplyProfileImage.cs` | 1 |
| Reply | `ReplySearchBar.cs` | 1 |

### Verified

- ✅ `dotnet test src/Microsoft.AndroidX.Compose.SourceGenerators.Tests` — 132/132
- ✅ `dotnet build src/Microsoft.AndroidX.Compose` — clean (no RS0016/RS0017)
- ✅ `dotnet build src/Microsoft.AndroidX.Compose.Gallery`
- ✅ `dotnet build samples/Jetchat`
- ✅ `dotnet build samples/JetNews`
- ✅ `dotnet build samples/Reply`

Not deployed to a device — leaving smoke-test for the user.

### Coordination

Round-2 #2. Disjoint file set from sibling round-2 PRs except for `PublicAPI.Unshipped.txt` — expect a mechanical sort conflict on merge with round-2 #1 (`Modifier.Padding` defaults) and round-2 #3 (`Func<IComposer, ComposableNode>` implicit).

Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants