Repository navigation
Add IComposer.MutableStateOf extension and implicit MutableState<T> → T - #229
Conversation
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]>
…le-state-of-ergonomics # Conflicts: # samples/Jetchat/Profile.cs
There was a problem hiding this comment.
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
MutableStateOfextension methods onIComposer(generic + four numeric overloads) andimplicit operator TonMutableState<T>, with full XML docs andPublicAPI.Unshipped.txtentries. - Primitive fast-path logic (
Kindenum,CreateState,ProbeKind, specializedValuegetter/setter) moved fromMutableNumberState<T>toMutableState<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))toc.MutableStateOf(x)across gallery demos and sample apps, plus staleusingcleanup.
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) |
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]>
Brainstorm suggestion #2 —
MutableStateOfergonomics. Bring the C# call site closer to Kotlin'svar count by remember { mutableStateOf(0) }.Before / after
Kotlin:
C# before:
C# after:
Three sub-changes (all landed)
1.
composer.MutableStateOf(initial)extension familySingle 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/doublevalues, soc.MutableStateOf(0)returnsMutableNumberState<int>and gets++/--for free, whilec.MutableStateOf("Ada")falls through to the genericMutableState<string>. Each overload forwards[CallerLineNumber]/[CallerFilePath]toRememberso call sites own a stable slot key.++c.MutableStateOf(0)intMutableNumberState<int>c.MutableStateOf(1000L)longMutableNumberState<long>c.MutableStateOf(0.5f)floatMutableNumberState<float>c.MutableStateOf(Math.PI)doubleMutableNumberState<double>c.MutableStateOf("Ada")MutableState<string>c.MutableStateOf(false)MutableState<bool>c.MutableStateOf<long?>(null)MutableState<long?>2. Implicit
MutableState<T> → Tif (count > 0),int x = state;,state + 5all light up.$"Count: {count}"interpolation keeps callingToString()(interpolation boxes args asobject, which doesn't trigger user-defined conversions), so existing formatting is preserved. Inherited byMutableNumberState<T>per the C# spec.HelloCounterDemo.csnow runtime-exercises the conversion via acount > 0 ? new Text(...) : nullline.3. Fold the primitive fast path into
MutableState<T>Kindprobe,CreateState(picksIMutableIntState/IMutableLongState/IMutableFloatState), specialisedValuegetter/setter, and re-probe onSetUnderlyingStateforRememberSaveableround-trip — all moved fromMutableNumberState<T>into the base. Now everynew MutableState<int>(0)(and the newc.MutableStateOf(0)) benefits from the primitive backing.MutableNumberState<T>stays as a thin 4-line subclass that only addsoperator ++/--(which still requiresT : INumber<T>).This was feasible because the fast-path machinery only checks
typeof(T)— it never needsINumber<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 fromc.Remember(() => new Mutable[Number]State<T>(x))toc.MutableStateOf(x). Sites needing explicit T for null literals (c.MutableStateOf<long?>(null)) handled by hand.RememberSaveable(() => new MutableNumberState<int>(0))left as-is —RememberSaveableis 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 sinceMutableState<TextFieldValue>isn't named at call sites anymore) were trimmed viadotnet format style --diagnostics IDE0005.Public API delta
PublicAPI.Unshipped.txt:MutableStateOfoverloads + oneMutableState<T>.implicit operator T.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— cleandotnet build samples/Jetchat,samples/JetNews,samples/Reply— all cleandotnet test src/Microsoft.AndroidX.Compose.SourceGenerators.Tests— 130/130 passNo
-t:Runper request — implicit-conversion exercise lives inHelloCounterDemofor 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)]onMutableNumberState<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.cscall sites. Merge conflicts onPublicAPI.Unshipped.txtat review time are expected and mechanical (re-sort).Co-authored-by: Copilot [email protected]