Yokan / rebuild
Course 1 8624561

Kotlin Multiplatform architecture review

7 min readSnapshot 8624561Markdown

Reviewed on 2026-10-25 against the pinned application and the corrected implementations taught in this guide.

Which code to implement

Use the reviewed implementation listings in the chapters and the reviewed source archive. They replace the affected baseline files and include their call-site wiring and regression tests. The implementation manifest records each replacement/addition, its reason, baseline hash and reviewed hash.

The original archive, file workbooks and browser source pages retain the immutable baseline for comparison. They intentionally do not silently become a different upstream revision. Unchanged files are identical in both archives. The original application checkout is not edited by this review.

Overall assessment

The application has a reasonable pragmatic KMP architecture: common contracts and policies, platform/intermediate source sets, repositories, explicit construction of profile-owned dependencies, and awaited native/network cleanup. KMP does not require Hilt, Koin, a use-case class per method, or one Gradle module per screen. Shared code must use dependencies supported by every target of its source set. KMP project structure.

The review scanned 593 baseline common Kotlin files and 52 ViewModel files for selected boundary/state hazards, then inspected the construction, state, publication and file-action paths changed below. The shared application scan found no Android/Java/native platform imports, GlobalScope, or plain collectAsState calls. This lexical scan is evidence for specific checks, not a semantic audit of every function or a certification of the entire codebase.

Concrete adjustments

Finding Reviewed implementation Verification
SourceLanguagesViewModel kept selection in both its UI state and a second mutable flow. Derive query selection from state; compare an incoming projection with current state inside the atomic update. Rapid media selection and unrelated source updates keep the latest media/groups together.
Source creation injected the complete database into a presentation class. Inject a small creation command returning the domain Source; capture its database dependency and mapping at the route boundary. An injected command can fail, succeed and clear its prior error; cancellation is rethrown.
Custom-button storage, ordering and mutation policy lived in the ViewModel. Add CustomButtonRepository and DatabaseCustomButtonRepository, with an injected clock; the ViewModel owns presentation state and delegates commands. Wire the adapter at the route boundary. Real memory-backend tests cover favorite/reorder behavior and immediate published UI state.
Favorite/reorder commands emitted intermediate multi-row snapshots and could clear a favorite for a stale target. Read authoritative rows inside the batch, ignore missing IDs, coalesce publication and update only changed rows with one command timestamp. Favorite/reorder each publish one coherent snapshot; an obsolete favorite ID leaves the existing favorite intact.
Diagnostic log reads and crash deletion ran synchronously from UI commands; crash-store helpers could swallow cancellation. Schedule file work on an injected blocking dispatcher, use async file ports, recheck cancellation before sharing, and retain cancellation in crash-store fallbacks. Inject sharing for tests. Sharing is deferred, uses the worker, and never shares/reveals on cancellation; cancelled deletion keeps displayed state.
Config regeneration used a CPU dispatcher as its default for blocking file work. Use the existing platform blockingDispatcher, retain dispatcher injection, and write through async ports before publishing success. No success before both writes complete.
Included training material claimed shared lifecycle collection was unavailable, showed destructive migration as a default, and passed non-Throwable errors into Result.failure. Correct the affected training references and replace the invalid Result example with Throwable failures. Replace blanket init-collector/line-count rules with ownership/responsibility guidance. The primary code keeps lifecycle-aware collection; guide checks validate the reviewed reference bytes and listings.

Related implementation steps are in repository boundaries, extension presentation, settings/integrations, and supporting guidance.

Dependency and pattern decisions

Boundary Appropriate design here Constraint
Root/platform entry → ProfileSession → feature graph Explicit constructor wiring and factories at the composition root. Capture dependencies once; a delayed command must not look up a later active profile.
UI state → command → repository → backend Unidirectional state and narrow repository/command ports where a feature benefits. UI content receives state/callbacks; persistence ordering does not belong in rendering.
HttpService and profile wrappers Adapter for platform transport, Decorator for ownership/headers/retry policy. Every wrapper preserves cancellation, errors and resource ownership.
Sync/media/runtime implementations Strategy where implementations share a real contract and can be substituted. A capability difference must remain visible; unsupported is not successful no-op behavior.
CustomButtonRepository A small facade over state-mirror reads and coordinated mutations. An interface is useful because it isolates policy and testing, not because every method needs another class.

These names describe existing responsibilities rather than requiring an inheritance hierarchy everywhere. Refactoring Guru's Strategy, Decorator and Facade explain the corresponding intent.

Manual dependency injection is a supported approach; a DI framework is an implementation choice. Use cases are useful for reusable or complex orchestration, rather than one-line delegation. Manual DI, domain-layer guidance.

State, lifecycle and coroutine rules

Expose read-only StateFlow. Keep state immutable and compute storage/network work outside update lambdas: an atomic update may retry its lambda. A whole-value assignment is already atomic; its presence alone does not prove a lost-update bug. Conditional read/modify/write and duplicated authorities require more care. StateFlow update contract.

Shared routes can collect with collectAsStateWithLifecycle using the multiplatform Lifecycle dependency and a valid owner. Keep the desktop Main dispatcher integration and explicit resource finalizers. Web lifecycle does not reliably reach DESTROYED; lifecycle collection alone is not a substitute for owned close/join paths. Compose Multiplatform lifecycle.

Inject execution contexts around potentially blocking work and keep suspend APIs main-safe. Preserve CancellationException rather than converting it into an ordinary UI failure or success fallback. Expected file failures may still use an explicit fallback. Coroutine best practices.

An owned collector in init is appropriate when reconciling synchronously published state; stateIn is appropriate for shared derived state. Do not replace every collector with WhileSubscribed: background work and final progress have different lifetime requirements. Dedicated cleanup jobs are deliberate when they are admitted once and explicitly joined, not automatically GlobalScope-style leaks.

Do not add Immutable/Stable annotations to every model as a shortcut. They are compiler contracts; val properties containing mutable arrays or collections do not become deeply immutable through annotation. Measure recomposition and preserve correct ownership/equality before optimizing. Compose stability guidance.

Batch coalesces publication; it does not promise rollback for arbitrary exceptions. Restore/trust installation needs the stronger expected-snapshot/backend transaction contracts already described in chapters 03, 07 and 20. Do not advertise a UI batch as an ACID transaction.

Modules and compatibility

The shared application remains a large Gradle module. Package boundaries do not enforce a strict Clean Architecture dependency graph. A later extraction can separate stable models/contracts, storage/network adapters and cohesive features, but moving packages into modules before removing cycles would not improve correctness. Preserve extension ABI names, schemas, serialized fields and native/profile lifetime contracts during that work.

This review makes focused feature boundaries concrete rather than claiming that every legacy database-facing ViewModel has been rewritten. YokanDatabase is already a multiplatform interface over a state mirror; it is not a concrete Room DAO. New code should prefer a narrower repository/command when it isolates meaningful policy, as the reviewed button/source examples do.

Toolchain/native artifacts remain pinned. In particular, the baseline's documented internal native release-cache switch remains an explicit compatibility constraint, not a promise of a stable compiler API. Changing native build flags or removing fallback backends requires the native release/device validation matrix, not a mechanical design-pattern refactor.

Reproduce the verification

From this guide:

python3 tools/check_kmp_architecture.py
python3 -m unittest discover -s tools -p 'test_*.py'
npm run guide:chapters
npm run guide:validate
npm run build
npm run check

Extract reviewed-source.zip into a separate application directory. With the Android SDK configured, run the focused shared tests on the desktop target:

./gradlew :composeApp:desktopTest --tests '*Guided*' --tests '*CrashReportStoreTest' --no-daemon

The tests use the real Kotlin/coroutine/lifecycle/database contracts, controlled dispatchers and the memory backend. They do not open native share UI or require a live service. Verification evidence records executed checks and remaining platform limits. Native device behavior, live integrations and all release packages remain separate acceptance gates.

Search chapters, reference and source filenames.