<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by George Karanikolas on Medium]]></title>
        <description><![CDATA[Stories by George Karanikolas on Medium]]></description>
        <link>https://medium.com/@seijind?source=rss-d690390b08a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*01NMGtIQczY_uY6xclm-jg@2x.jpeg</url>
            <title>Stories by George Karanikolas on Medium</title>
            <link>https://medium.com/@seijind?source=rss-d690390b08a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:01:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seijind/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Room Database in the Browser: Kotlin/Wasm and SQLite with OPFS]]></title>
            <link>https://medium.com/@seijind/room-database-in-the-browser-kotlin-wasm-and-sqlite-with-opfs-9c32cc6def61?source=rss-d690390b08a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c32cc6def61</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[George Karanikolas]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 06:19:03 GMT</pubDate>
            <atom:updated>2026-04-14T06:19:03.744Z</atom:updated>
            <content:encoded><![CDATA[<p>Build a fully persistent, offline-capable web app using Room 3.0 and WebAssembly.</p><p>Room 3.0 shipped with Kotlin Multiplatform support, and tucked inside that release is something most developers missed: <strong>web support</strong>. Not “web” as in REST APIs. Actual Room database operations, running client-side in the browser, powered by SQLite compiled to WebAssembly and storing data in the Origin Private File System (OPFS).</p><p>This article walks through a minimal working example — a Note-taking app — to show exactly how this works, what the moving parts are, and where the gotchas hide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xevq_J8ln2QNHssCFqJI5Q.png" /></figure><h2>The Big Picture</h2><p>On Android, Room talks to SQLite through the Android framework. On iOS and Desktop, it uses native SQLite bindings. On the web, there’s no native SQLite — so Room needs a different path.</p><p>The solution is a three-layer bridge:</p><ol><li><strong>Room</strong> (Kotlin, commonMain) — your Entity, DAO, and Database classes, identical to Android</li><li><strong>WebWorkerSQLiteDriver</strong> (AndroidX artifact sqlite-web) — a Kotlin/Wasm driver that communicates via postMessage</li><li><strong>Web Worker</strong> (JavaScript) — runs @sqlite.org/sqlite-wasm in a dedicated thread with OPFS for persistent storage</li></ol><p>Why a Web Worker? Because OPFS — the browser API that gives you actual file system access for persistent storage — only works inside Worker threads. The main thread can’t touch it. This is a browser security constraint, not a Room design choice.</p><pre>┌─────────────────────────────────────────────────────┐<br>│                    commonMain                       │<br>│  ┌──────────┐  ┌──────────┐  ┌───────────────────┐  │<br>│  │NoteEntity│  │ NoteDao  │  │   AppDatabase     │  │<br>│  │ @Entity  │  │  @Dao    │  │ @ConstructedBy    │  │<br>│  └──────────┘  └──────────┘  └───────────────────┘  │<br>│                                    │                │<br>│                       expect getDatabaseBuilder()   │<br>└────────────────────────────────────┬────────────────┘<br>                                     │<br>┌────────────────────────────────────▼────────────────┐<br>│                   wasmJsMain                        │<br>│                                                     │<br>│  actual fun getDatabaseBuilder()                    │<br>│    Room.databaseBuilder(name = &quot;notes.db&quot;)          │<br>│      .setDriver(WebWorkerSQLiteDriver(...))         │<br>│                         │                           │<br>│            @JsFun → new Worker(&#39;worker.js&#39;)         │<br>│                    Web Worker thread                │<br>│                  ┌──────────────────┐               │<br>│                  │ SQLite WASM      │               │<br>│                  │ OPFS storage     │               │<br>│                  └──────────────────┘               │<br>└─────────────────────────────────────────────────────┘</pre><h2>Step 1 — Dependencies</h2><p>Starting with the version catalog. Room 3 uses the androidx.room3 group ID — not the old androidx.room. Same goes for the Gradle plugin.</p><p><strong>gradle/libs.versions.toml</strong></p><pre>[versions]<br>room   = &quot;3.0.0-alpha03&quot;<br>sqlite = &quot;2.7.0-alpha03&quot;<br>ksp    = &quot;2.3.6&quot;<br>koin   = &quot;4.2.0&quot;</pre><pre>[libraries]<br>room-runtime  = { group = &quot;androidx.room3&quot;, name = &quot;room3-runtime&quot;, version.ref = &quot;room&quot; }<br>room-compiler = { group = &quot;androidx.room3&quot;, name = &quot;room3-compiler&quot;, version.ref = &quot;room&quot; }<br>sqlite-web    = { group = &quot;androidx.sqlite&quot;, name = &quot;sqlite-web&quot;, version.ref = &quot;sqlite&quot; }<br>koin-core     = { module = &quot;io.insert-koin:koin-core&quot;, version.ref = &quot;koin&quot; }<br>koin-compose-viewmodel = { module = &quot;io.insert-koin:koin-compose-viewmodel&quot;, version.ref = &quot;koin&quot; }</pre><pre>[plugins]<br>ksp  = { id = &quot;com.google.devtools.ksp&quot;, version.ref = &quot;ksp&quot; }<br>room = { id = &quot;androidx.room3&quot;, version.ref = &quot;room&quot; }</pre><h2>Step 2 — Gradle Setup</h2><p>The composeApp/build.gradle.kts needs the KSP and Room plugins, plus a few web-specific dependencies.</p><pre>plugins {<br>    alias(libs.plugins.kotlinMultiplatform)<br>    alias(libs.plugins.composeMultiplatform)<br>    alias(libs.plugins.composeCompiler)<br>    alias(libs.plugins.ksp)<br>    alias(libs.plugins.room)<br>}</pre><pre>kotlin {<br>    wasmJs {<br>        browser()<br>        binaries.executable()<br>    }</pre><pre>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(libs.room.runtime)<br>            implementation(libs.koin.core)<br>            implementation(libs.koin.compose.viewmodel)<br>            // + Compose dependencies<br>        }<br>        wasmJsMain.dependencies {<br>            implementation(libs.sqlite.web)<br>            implementation(npm(&quot;@sqlite.org/sqlite-wasm&quot;, &quot;3.50.1-build1&quot;))<br>            implementation(npm(&quot;sqlite-wasm-worker&quot;, project.file(&quot;sqlite-wasm-worker&quot;)))<br>        }<br>    }<br>}</pre><pre>dependencies {<br>    add(&quot;kspWasmJs&quot;, libs.room.compiler)<br>}</pre><pre>extensions.configure&lt;androidx.room3.gradle.RoomExtension&gt; {<br>    schemaDirectory(&quot;$projectDir/schemas&quot;)<br>}</pre><p>Two things worth noting:</p><ul><li>npm(&quot;sqlite-wasm-worker&quot;, project.file(&quot;sqlite-wasm-worker&quot;)) — this points to a local npm package (more on that next)</li><li>kspWasmJs — KSP runs code generation only for the wasmJs target</li></ul><h2>Step 3 — The SQLite Web Worker</h2><p>This is the part that doesn’t exist on any other platform. The WebWorkerSQLiteDriver from AndroidX doesn&#39;t ship with a default worker yet (planned for a future release). For now, you need to include one yourself.</p><p>The good news: there’s an <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:sqlite/sqlite-web-worker-test/web-worker/worker.js">official reference implementation</a> in the AndroidX source tree. It’s a JavaScript file that runs inside a Web Worker, manages SQLite connections and prepared statements, and communicates with the Kotlin side via postMessage.</p><p>Create a local npm package at composeApp/sqlite-wasm-worker/:</p><p><strong>package.json</strong></p><pre>{<br>    &quot;name&quot;: &quot;sqlite-wasm-worker&quot;,<br>    &quot;version&quot;: &quot;0.0.0&quot;,<br>    &quot;license&quot;: &quot;APACHE-2.0&quot;,<br>    &quot;dependencies&quot;: {<br>        &quot;@sqlite.org/sqlite-wasm&quot;: &quot;^3.50.1-build1&quot;<br>    }<br>}</pre><p><strong>worker.js</strong> — handles four commands:</p><p>Each message carries a numeric id for request/response correlation. The protocol is specified in the <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:sqlite/sqlite-web/src/commonMain/kotlin/androidx/sqlite/driver/web/WebWorkerSQLiteDriver.kt">WebWorkerSQLiteDriver KDoc</a>.</p><p>The full worker.js is in the <a href="https://github.com/SeijinD/KMPWebRoom">repository</a>. It&#39;s the official AndroidX reference with Apache 2.0 license header intact.</p><h2>Step 4 — CORS Headers (Don’t Skip This)</h2><p>OPFS requires SharedArrayBuffer, which browsers gate behind two security headers. Without them, the Worker silently fails and nothing gets saved.</p><p><strong>composeApp/webpack.config.d/cors-headers.js</strong></p><pre>;(function (config) {<br>    config.devServer = config.devServer || {};<br>    config.devServer.headers = [<br>        { key: &#39;Cross-Origin-Opener-Policy&#39;, value: &#39;same-origin&#39; },<br>        { key: &#39;Cross-Origin-Embedder-Policy&#39;, value: &#39;require-corp&#39; }<br>    ];<br>})(config);</pre><p>This bit me during development. The app loaded fine, the UI rendered, but clicking “Add” did nothing. No errors in the console. If you’re debugging and everything looks correct but data isn’t persisting — check these headers first.</p><blockquote>For production deployments, your web server (Nginx, Cloudflare, etc.) needs to serve these headers too.</blockquote><h2>Step 5 — Room Layer (commonMain)</h2><p>This is where things feel familiar. The Entity, DAO, and Database are standard Room code — no platform-specific annotations, no #ifdef, nothing.</p><p><strong>NoteEntity.kt</strong></p><pre>@Entity(tableName = &quot;notes&quot;)<br>data class NoteEntity(<br>    @PrimaryKey(autoGenerate = true) val id: Long = 0,<br>    val text: String<br>)</pre><p><strong>NoteDao.kt</strong></p><pre>@Dao<br>interface NoteDao {<br>    @Query(&quot;SELECT * FROM notes ORDER BY id DESC&quot;)<br>    fun observeAll(): Flow&lt;List&lt;NoteEntity&gt;&gt;</pre><pre>    @Upsert<br>    suspend fun upsert(note: NoteEntity)</pre><pre>    @Query(&quot;DELETE FROM notes WHERE id = :id&quot;)<br>    suspend fun deleteById(id: Long)<br>}</pre><p><strong>AppDatabase.kt</strong></p><pre>@Database(<br>    entities = [NoteEntity::class],<br>    version = 1<br>)<br>@ConstructedBy(AppDatabaseConstructor::class)<br>abstract class AppDatabase : RoomDatabase() {<br>    abstract fun noteDao(): NoteDao<br>}</pre><pre>@Suppress(&quot;KotlinNoActualForExpect&quot;)<br>expect object AppDatabaseConstructor : RoomDatabaseConstructor&lt;AppDatabase&gt; {<br>    override fun initialize(): AppDatabase<br>}</pre><p>@ConstructedBy is the Room 3 KMP pattern. It replaces the old Room.databaseBuilder(context) that required an Android Context. The Room compiler generates the actual implementation automatically via KSP — you don&#39;t write it yourself.</p><h2>Step 6 — Database Builder (expect/actual)</h2><p>The only platform-specific code in the entire data layer.</p><p><strong>commonMain — expect declaration:</strong></p><pre>expect fun getDatabaseBuilder(): RoomDatabase.Builder&lt;AppDatabase&gt;</pre><p><strong>wasmJsMain — the web-specific actual:</strong></p><pre>actual fun getDatabaseBuilder(): RoomDatabase.Builder&lt;AppDatabase&gt; {<br>    return Room.databaseBuilder&lt;AppDatabase&gt;(<br>        name = &quot;notes.db&quot;,<br>        factory = { AppDatabaseConstructor.initialize() }<br>    ).setDriver(WebWorkerSQLiteDriver(createSQLiteWorker()))<br>}</pre><pre>@JsFun(&quot;() =&gt; new Worker(new URL(&#39;sqlite-wasm-worker/worker.js&#39;, import.meta.url), { type: &#39;module&#39; })&quot;)<br>private external fun createSQLiteWorker(): Worker</pre><p>Three things happening here:</p><ul><li><strong>WebWorkerSQLiteDriver</strong> — the SQLite driver from androidx.sqlite:sqlite-web that talks to the Web Worker via postMessage</li><li><strong>@JsFun</strong> — Kotlin/Wasm JS interop annotation. It creates the Worker from JavaScript. Note: don&#39;t use js() inline expressions in Kotlin/Wasm — it can crash the compiler in certain contexts</li><li><strong>factory</strong> — instead of passing an Android Context, we pass a lambda that calls the KSP-generated constructor</li></ul><p>That’s it. These few lines are the only web-specific code in the entire data layer.</p><h2>Step 7 — Wiring It Up</h2><p><strong>Koin module:</strong></p><pre>val appModule = module {<br>    single { getDatabaseBuilder().build() }<br>    single { get&lt;AppDatabase&gt;().noteDao() }<br>    viewModelOf(::NotesViewModel)<br>}</pre><p><strong>ViewModel:</strong></p><pre>class NotesViewModel(private val dao: NoteDao) : ViewModel() {<br>    val notes = dao.observeAll()<br>        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())</pre><pre>    fun addNote(text: String) {<br>        viewModelScope.launch { dao.upsert(NoteEntity(text = text)) }<br>    }</pre><pre>    fun deleteNote(id: Long) {<br>        viewModelScope.launch { dao.deleteById(id) }<br>    }<br>}</pre><p><strong>Entry point (wasmJsMain):</strong></p><pre>fun main() {<br>    startKoin { modules(appModule) }<br>    ComposeViewport { App() }<br>}</pre><h2>What You Get</h2><p>Run ./gradlew composeApp:wasmJsBrowserDevelopmentRun, open localhost:8080, and you have a Note app backed by a real SQLite database running entirely in the browser. Add some notes, refresh the page — they&#39;re still there. That&#39;s OPFS doing its job.</p><p>The shared code in commonMain (Entity, DAO, Database, ViewModel) is <strong>identical</strong> to what you&#39;d write for an Android app. The web-specific code is limited to:</p><ul><li>DatabaseBuilder.wasmJs.kt — 8 lines</li><li>worker.js — the official AndroidX reference</li><li>cors-headers.js — 6 lines</li></ul><p>Everything else is shared.</p><h2>Things to Keep in Mind</h2><p><strong>Browser support.</strong> OPFS requires Chromium 102+ (mid-2022), Firefox 111+, or Safari 16.4+. Older browsers won’t work.</p><p><strong>Alpha status.</strong> Room 3.0 and sqlite-web are in alpha. APIs may change. Don&#39;t ship production apps against alpha artifacts without accepting that risk.</p><p><strong>No default worker (yet).</strong> The WebWorkerSQLiteDriver doesn&#39;t bundle a worker.js. You have to include the <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:sqlite/sqlite-web-worker-test/web-worker/worker.js">reference implementation</a> yourself. The AndroidX team has said they plan to publish one via NPM in a future release.</p><p><strong>CORS headers are mandatory.</strong> SharedArrayBuffer — which OPFS depends on — requires Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. Miss these and the database silently fails with no errors.</p><h2>When Does This Actually Make Sense?</h2><p>Having a real SQL database in the browser isn’t necessary for every project. However, in specific scenarios, it can be transformative:</p><ul><li><strong>One codebase, multiple platforms.</strong> Share a single Room data layer across Android, Desktop, and Web, eliminating duplicated data logic and reducing maintenance overhead.</li><li><strong>Local-first and privacy-focused apps.</strong> Keep user data entirely on-device with OPFS-backed storage, avoiding backend infrastructure and compliance complexities.</li><li><strong>Offline-capable PWAs.</strong> Enable robust functionality in low-connectivity environments such as field operations, conferences, or internal enterprise tools.</li><li><strong>Rapid prototyping and MVPs.</strong> Build and validate ideas quickly with persistent storage and zero infrastructure, adding a backend only when necessary.</li><li><strong>Complex client-side querying.</strong> Leverage the full power of SQL — JOINs, aggregations, window functions, and full-text search — far beyond the capabilities of localStorage or IndexedDB.</li></ul><h2>References</h2><ul><li><a href="https://developer.android.com/jetpack/androidx/releases/room3">Room 3.0 Release Notes</a></li><li><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:sqlite/sqlite-web/src/commonMain/kotlin/androidx/sqlite/driver/web/WebWorkerSQLiteDriver.kt">WebWorkerSQLiteDriver protocol spec (KDoc)</a></li><li><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:sqlite/sqlite-web-worker-test/web-worker/worker.js">Official worker.js — AndroidX source tree</a></li><li><a href="https://developer.chrome.com/blog/sqlite-wasm-in-the-browser-backed-by-the-origin-private-file-system">SQLite Wasm + OPFS — Chrome Blog</a></li><li><a href="https://sqlite.org/wasm/doc/trunk/persistence.md">SQLite Wasm persistence docs</a></li><li><a href="https://android-developers.googleblog.com/2026/03/room-30-modernizing-room.html">Room 3.0 announcement — Android Developers Blog</a></li></ul><p>Grab the source code: <a href="https://github.com/SeijinD/KMPWebRoom"><strong>KMPWebRoom Repository</strong></a></p><p>Let’s connect! Find me on <a href="https://github.com/SeijinD">GitHub</a> &amp; <a href="https://www.linkedin.com/in/seijind">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c32cc6def61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Patterns Behind a Production RSS Monitor in Kotlin]]></title>
            <link>https://medium.com/@seijind/5-patterns-behind-a-production-rss-monitor-in-kotlin-1801490b3243?source=rss-d690390b08a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1801490b3243</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[telegram]]></category>
            <dc:creator><![CDATA[George Karanikolas]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 13:06:21 GMT</pubDate>
            <atom:updated>2026-03-26T13:06:21.453Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Parallel polling, conditional HTTP requests, and Telegram notifications</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tgU8oMKrJ4Bkp_tconJLA.jpeg" /></figure><p>Most RSS readers start the same way. A for loop, a URL, an XML parser. You ship it, it works, and you move on. Then you add more feeds, and somewhere around feed number thirty, the polling cycle starts taking longer than the interval itself. That&#39;s when &quot;simple&quot; stops being a virtue.</p><p>This article walks through <strong>Telefeed</strong> — a reference implementation for a concurrent RSS monitoring service. It&#39;s built around five patterns that, together, turn a naive poller into something you&#39;d actually run in production. Notifications are delivered via Telegram, but the delivery layer is designed to be swapped out easily.</p><h3>Why RSS?</h3><p>RSS gets written off a lot. &quot;Nobody uses that anymore.&quot; In practice, it&#39;s still the backbone of blogs, news sites, release notes, security advisories, and changelogs. Unlike web scraping, RSS is a structured, stable format designed specifically for change detection and content syndication — you get clean data without parsing HTML or dealing with layout changes breaking your selectors.</p><p>If you&#39;re monitoring external sources for updates, RSS is often the most reliable option available.</p><h3>System Architecture</h3><p>Telefeed is structured as a straightforward pipeline. Every poll cycle runs through the same seven steps:</p><pre>Polling Loop<br>    → Fetch feeds (parallel, async/awaitAll)<br>        → Conditional request (ETag / If-Modified-Since)<br>            → Parse XML (XXE-hardened)<br>                → Detect new items<br>                    → Update state (Mutex + immutable data class)<br>                        → Send notification (Telegram Bot API)</pre><p>Steps 1 through 5 map directly to the five patterns below. The notification layer is covered separately.</p><h3>The Problem With Sequential Polling</h3><p>Here&#39;s what a straightforward implementation looks like at its core:</p><pre>for (feed in feeds) {<br>    val content = fetch(feed)<br>    val items = parse(content)<br>    notify(items)<br>}</pre><p>Clean and readable. But every fetch call blocks until the server responds. With 100 feeds averaging 500ms each, your polling cycle takes 50 seconds before a single line of business logic runs. That&#39;s not a performance concern — it&#39;s a design flaw.</p><h3>1. Parallel I/O with Structured Concurrency</h3><p>The fix is straightforward in Kotlin: replace the sequential loop with async/awaitAll inside a coroutineScope.</p><pre>suspend fun checkFeeds() = coroutineScope {<br>    subscriptions.map { sub -&gt;<br>        async { processSubscription(sub) }<br>    }.awaitAll()<br>}</pre><p>All feeds are fetched concurrently. The total cycle time is now bounded by the <strong>slowest single feed</strong>, not the sum of all of them. Importantly, coroutineScope gives you structured concurrency for free — if one coroutine throws, the scope cancels the rest and propagates the failure cleanly.</p><p>No thread pools to manage. No ExecutorService boilerplate.</p><h3>2. Conditional Requests (ETags and Last-Modified)</h3><p>Here&#39;s something most implementations skip: most of the time, feeds haven&#39;t changed. Downloading the full XML payload just to find nothing new is wasteful — on bandwidth, on CPU, and on the feed server&#39;s resources.</p><p>HTTP has had a solution for this since the 90s. When a server returns an ETag or Last-Modified header, you can store it and send it back on the next request:</p><pre>val request = HttpRequest.newBuilder()<br>    .uri(URI.create(sub.url))<br>    .apply {<br>        sub.lastEtag?.let { header(&quot;If-None-Match&quot;, it) }<br>        sub.lastModified?.let { header(&quot;If-Modified-Since&quot;, it) }<br>    }<br>    .GET()<br>    .build()</pre><p>If nothing has changed, the server responds with 304 Not Modified — no body, no parsing. In Telefeed, a 304 is handled explicitly:</p><pre>when (response.statusCode()) {<br>    304 -&gt; null  // skip parsing entirely<br>    in 200..299 -&gt; response<br>    else -&gt; error(&quot;HTTP ${response.statusCode()} for ${sub.url}&quot;)<br>}</pre><p>For any feed that updates infrequently (which is most of them), this is the single biggest efficiency win you can make.</p><h3>3. XXE Protection — Don&#39;t Skip This</h3><p>If you&#39;re parsing XML from third-party URLs, you&#39;re parsing untrusted input. XML parsers support a feature called External Entity processing (XXE) that, if left enabled, can allow a malicious feed to read local files or make server-side requests from your machine.</p><p>The fix is a few lines on the DocumentBuilderFactory:</p><pre>private val xmlFactory = DocumentBuilderFactory.newInstance().apply {<br>    setFeature(&quot;http://apache.org/xml/features/disallow-doctype-decl&quot;, true)<br>    setFeature(&quot;http://xml.org/sax/features/external-general-entities&quot;, false)<br>    setFeature(&quot;http://xml.org/sax/features/external-parameter-entities&quot;, false)<br>    isXIncludeAware = false<br>    isExpandEntityReferences = false<br>}</pre><p>This is one of those things that&#39;s easy to forget because it never causes a visible problem — right up until it does. Lock it down from the start.</p><h3>4. Thread-Safe State Without the Headaches</h3><p>With dozens of coroutines running concurrently, shared mutable state becomes a problem fast. If two coroutines both update the same subscription metadata at the same time, you get lost writes.</p><p>Telefeed handles this with a combination of <strong>immutable data classes</strong> and a <strong>Mutex</strong> — a pattern that&#39;s sometimes called &quot;Redux-lite&quot; for coroutines:</p><pre>private val stateMutex = Mutex()<br><br>private suspend fun updateSubscriptionState(<br>    subId: Int,<br>    latestLink: String,<br>    etag: String? = null,<br>    lastModified: String? = null<br>) {<br>    stateMutex.withLock {<br>        subscriptions = subscriptions.map {<br>            if (it.id == subId) it.copy(<br>                lastSeenLink = latestLink,<br>                lastEtag = etag ?: it.lastEtag,<br>                lastModified = lastModified ?: it.lastModified<br>            ) else it<br>        }<br>    }<br>}</pre><p>Because Subscription is a data class, copy() produces a new object rather than mutating the existing one. The Mutex ensures only one coroutine swaps the list at a time. No synchronized blocks, no AtomicReference gymnastics — just a clear, auditable update path.</p><h3>5. Drift-Compensated Polling</h3><p>A delay(60_000) at the end of your loop does not give you a 60-second interval. It gives you a 60-second interval, <em>plus however long the work took</em>. For a fast service, this barely matters, but if feed processing takes 5 seconds, you&#39;re already running 8% behind schedule. Over a day that compounds.</p><p>The fix is to measure the work and subtract it from the delay:</p><pre>while (isActive) {<br>    val elapsed = measureTimeMillis {<br>        checkFeeds()<br>    }<br>    val delayTime = (POLL_INTERVAL_MS - elapsed).coerceAtLeast(0)<br>    delay(delayTime)<br>}</pre><p>coerceAtLeast(0) handles the edge case where the work takes longer than the interval — instead of passing a negative value to delay, you just start the next cycle immediately.</p><h3>The Notification Layer</h3><p>Detecting new items is only half the job. Telefeed ships with a Telegram integration as the notification backend — a non-blocking JSON call to the Bot API, dispatched on Dispatchers.IO:</p><pre>private suspend fun sendTelegramMessage(chatId: Long, text: String) = withContext(Dispatchers.IO) {<br>    val payload = buildJsonObject {<br>        put(&quot;chat_id&quot;, chatId)<br>        put(&quot;text&quot;, text)<br>        put(&quot;parse_mode&quot;, &quot;HTML&quot;)<br>    }.toString()<br><br>    val request = HttpRequest.newBuilder()<br>        .uri(URI.create(&quot;https://api.telegram.org/bot$BOT_TOKEN/sendMessage&quot;))<br>        .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>        .POST(HttpRequest.BodyPublishers.ofString(payload))<br>        .build()<br><br>    httpClient.send(request, HttpResponse.BodyHandlers.ofString())<br>}</pre><p>Telegram is a convenient default — it&#39;s free, has a straightforward Bot API, and works well for personal or team alerting. But the sendNotification function is intentionally thin: it receives a chatId and an RssItem, formats the message, and delegates. Swapping Telegram for Slack (an incoming webhook), an SMTP client, a Discord bot, or a custom HTTP endpoint is a matter of replacing that one function. The rest of the pipeline — fetching, parsing, deduplication, state management — doesn&#39;t care.</p><p>This separation is worth keeping in mind if you adapt this for your own use case. The polling engine and the delivery mechanism are independent concerns, and they should stay that way.</p><h3>Putting It Together</h3><p>None of these five patterns is complicated on its own. The point is that they work together:</p><ul><li><strong>Coroutines</strong> make parallel I/O trivial to write and reason about.</li><li><strong>Conditional requests</strong> ensure you only do real work when there&#39;s real work to do.</li><li><strong>XXE hardening</strong> means you&#39;re not betting your service&#39;s security on every feed author being trustworthy.</li><li><strong>Mutex + immutability</strong> keeps shared state clean without fighting the coroutine model.</li><li><strong>Drift compensation</strong> means your scheduler behaves like a scheduler.</li></ul><p>These patterns aren&#39;t specific to RSS. They apply to any system that periodically polls external resources, detects changes, and triggers downstream actions — price trackers, availability monitors, health checks, sync services, crawlers. The domain changes; the architecture doesn&#39;t.</p><h3>Performance Notes</h3><p>The gains from these patterns are straightforward to reason about, even without benchmarks:</p><pre>Sequential polling:<br>100 feeds × 500ms avg = ~50s per cycle<br><br>Concurrent polling:<br>Cycle time ≈ slowest single feed</pre><p>Conditional requests compound this further. Most feeds don&#39;t update on every poll — when the server returns 304, there&#39;s no body to download and no XML to parse. In practice, concurrency and conditional requests together reduce both network traffic and CPU usage significantly for any real-world feed list.</p><h3>Possible Improvements</h3><p>Telefeed is intentionally minimal — a reference, not a finished product. Some natural next steps if you&#39;re building on top of it:</p><ul><li>Persist subscription state to a database instead of in-memory</li><li>Add exponential backoff for feeds that repeatedly fail</li><li>Support per-feed polling intervals</li><li>Add structured logging and metrics</li><li>Containerize and deploy as a background service</li></ul><h3>Wrapping Up</h3><p>Telefeed started as a practical itch — I already use Telegram daily, and I wanted a single place to see updates from the feeds I follow without opening five different tabs. The five patterns here aren’t exotic. They’re just the things you eventually learn to reach for when a naive implementation stops being good enough.</p><p>The full implementation is available <a href="https://gist.github.com/SeijinD/87e7e84bea243e8cc17f910cc7ce43f7">on GitHub</a>. If you end up adapting it for something other than RSS, I’d be curious to hear what you built with it.</p><p>Let’s connect! Find me on <a href="https://github.com/seijind">GitHub</a> &amp; <a href="https://www.linkedin.com/in/seijind/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1801490b3243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claim Before You Reveal: Engineering a Flip-to-Win Experience in Jetpack Compose]]></title>
            <link>https://medium.com/@seijind/claim-before-you-reveal-engineering-a-flip-to-win-experience-in-jetpack-compose-6f4f6e9fece6?source=rss-d690390b08a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f4f6e9fece6</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[George Karanikolas]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 10:56:10 GMT</pubDate>
            <atom:updated>2026-03-19T10:56:10.276Z</atom:updated>
            <content:encoded><![CDATA[<p>“Flip to Win” is a deceptively simple mechanic. The user picks a card, a prize is revealed, and maybe the rest of the grid flips too. Looks easy to build — but if you want it to feel right, there’s a lot of timing, state management, and architecture discipline hiding underneath.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTfkbIxHrqt5iZDnRhfrWw.png" /></figure><p>This post walks through the design decisions I made building <a href="https://github.com/SeijinD/FlipToWin"><strong>FlipToWin</strong></a>, an open-source Jetpack Compose library for this exact use case.</p><h2>Why This Is Harder Than It Looks</h2><p>A card flip is not a single animation, it’s a choreographed sequence. Here’s what happens from a single tap:</p><ol><li>All cards stop wiggling and become non-interactive.</li><li>The backend is called to confirm the reward — <strong>before any visual reveal</strong>. If the claim fails, the sequence stops here and the grid resets — the user never sees a prize they haven’t been granted.</li><li>The selected card scales up and slides to the center of the screen.</li><li>The card performs a 180° Y-axis rotation.</li><li>At exactly the 90° midpoint (when the card is edge-on and invisible), the card-back image is swapped for the reward image.</li><li>The card returns to its position.</li><li>Optionally, all remaining cards flip to reveal what was behind them, with shuffled, non-duplicate rewards.</li><li>The game resets and emits the result.</li></ol><p>Get the timing wrong at any step and the illusion breaks: a blank card flashes, an image appears backwards, or the grid jumps into its final state before the user has processed what happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*76elOGDFhuol83eWeTGJ2g.gif" /></figure><h2>State-Driven Animation: No Callback Chains</h2><p>The core design decision was to represent every visual property of every card as a field in an immutable data class:</p><pre>data class FlipToWinUiCard(<br>    val type: Int? = null, // null means the card is unrevealed (face-down)<br>    val imageUrl: String = &quot;&quot;,<br>    val brush: Brush? = null,<br>    val isClickable: Boolean = false,<br>    val isWiggling: Boolean = false,<br>    val isZoomed: Boolean = false,<br>    val isCentered: Boolean = false,<br>    val isFlipped: Boolean = false,<br>    val isSelected: Boolean = false,<br>)</pre><p>The ViewModel emits a new FlipToWinUiState (backed by a StateFlow) by toggling these fields in sequence, with delay() calls between steps. Each flag directly drives a remember { Animatable(...) } inside a LaunchedEffect. No animation controller objects, no callback chains, no mutable shared state. Just data flowing down the tree.</p><p>The <strong>midpoint swap</strong> — changing the card’s visual at the 90° rotation point — becomes trivial with this model. The ViewModel simply waits CARD_FLIP_MIDPOINT_MS = 350L (half the 700ms flip duration) and then updates imageUrl and brush. Compose re-renders with the reward image at the precise moment the card is invisible.</p><p>One subtle modeling decision worth calling out: the reward catalog uses a separate FlipToWinUiRewardVisual type — a lightweight model with no animation state — keeping FlipToWinUiCard focused solely on what&#39;s visible and interactive in the grid.</p><h2>The Backend Claim Happens Before the Animation</h2><p>This is worth highlighting because it’s easy to get backwards. In many implementations, the animation plays first and the backend is called at the end — which creates a window where the user sees their prize before it’s actually confirmed.</p><p>In FlipToWin, claimReward() is called the instant the user taps:</p><pre>fun onCardClicked(index: Int) {<br>    viewModelScope.launch {<br>        // Lock the UI immediately<br>        updateCards { it.copy(isWiggling = false, isClickable = false) }</pre><pre>        when (val result = claimRewardUseCase(winType)) {<br>            is FlipToWinClaimResult.Success -&gt; {<br>                // Only now do we start the animation sequence<br>                updateCard(index) { it.copy(isSelected = true, type = winType) }<br>                delay(BEFORE_SELECTED_CARD_MOVE_MS)<br>                updateCard(index) { it.copy(isZoomed = true, isCentered = true) }<br>            }<br>            is FlipToWinClaimResult.Error -&gt; {<br>                // Rollback: re-enable the grid and surface the error<br>                updateCards { it.copy(isClickable = true) }<br>                startWiggleWithDelay()<br>                _claimErrorEvent.emit(result.message)<br>            }<br>        }<br>    }<br>}</pre><p>The zoom and center are intentionally split into a separate step — a small delay between selection and movement gives the user a moment to register which card they picked before it starts animating.</p><p>If the claim fails, the grid rolls back gracefully — cards become tappable again, wiggling resumes, and an error event is emitted.</p><h2>Mirror Correction During 3D Rotation</h2><p>A subtle Compose quirk: when rotationY goes past 90°, the content renders mirrored. This happens because graphicsLayer applies rotationY in the coordinate space before rendering — once the card passes the edge-on point, the X axis is effectively flipped. The fix is a compensating scaleX:</p><pre>.graphicsLayer {<br>    val rotation = rotationYProvider()<br>    scaleX = if (abs(rotation) &gt; 90f) -1f else 1f<br>}</pre><p>Applied only to the image layer, this keeps icons and text correctly oriented throughout the full 180° rotation without any additional composable nesting.</p><h2>Architecture: Three Layers, One Contract</h2><p>The library is organized into Domain, Data, and UI layers. The public surface is minimal:</p><ul><li><strong>Domain</strong>: The FlipToWinRepository interface with two suspend functions — getGame() and claimReward(). Sealed result types (FlipToWinLoadResult, FlipToWinClaimResult) make exhaustive error handling natural.</li><li><strong>Data</strong>: Ships with a MockFlipToWinRepository. In your project, you provide your own implementation via a Hilt module.</li><li><strong>UI</strong>: A @HiltViewModel that exposes a single StateFlow&lt;FlipToWinUiState&gt; and three SharedFlow channels for result, error, and claim-error events.</li></ul><p>The integration on the consumer side is a single composable:</p><pre>FlipToWinScreen(<br>    viewModel = hiltViewModel(),<br>    onResult = { rewardType -&gt; /* grant reward */ },<br>    onError = { code -&gt; /* handle init failure */ },<br>    onClaimError = { message -&gt; /* show retry */ },<br>)</pre><h2>Image Pre-loading</h2><p>Since reward images are loaded from remote URLs, there’s a risk of visible loading during the reveal. To avoid this, the grid pre-fetches all image URLs (both card-backs and rewards) as soon as the state is available:</p><pre>LaunchedEffect(uiState.cards, uiState.rewardCatalog) {<br>    val allUrls = (uiState.cards.map { it.imageUrl } +<br>                   uiState.rewardCatalog.map { it.imageUrl })<br>        .filter { it.isNotEmpty() }<br>        .distinct()</pre><pre>    allUrls.forEach { url -&gt;<br>        context.imageLoader.enqueue(<br>            ImageRequest.Builder(context)<br>                .data(url)<br>                .memoryCachePolicy(CachePolicy.ENABLED)<br>                .diskCachePolicy(CachePolicy.ENABLED)<br>                .build()<br>        )<br>    }<br>}</pre><p>By the time the user picks a card, the reward image is already in Coil’s memory cache. The reveal feels instant.</p><h2>Key Takeaway</h2><p>The approach here is nothing exotic: model everything as immutable state, drive animations reactively via Animatable + LaunchedEffect, and use delay() in the ViewModel to sequence mutations in time. What makes it solid is the discipline of keeping that pattern consistent across every step — including the backend handshake — so there&#39;s never a moment where the UI and the server are out of sync.</p><p><strong>Grab the source code:</strong> 👉 <a href="https://github.com/SeijinD/FlipToWin">FlipToWin Repository</a></p><p><strong>Let’s connect!</strong> Find me on <a href="https://github.com/SeijinD">GitHub</a> &amp; <a href="https://www.linkedin.com/in/seijind/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f4f6e9fece6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing 20 @Preview Functions — Build a Runtime Sandbox Instead]]></title>
            <link>https://medium.com/@seijind/stop-writing-20-preview-functions-build-a-runtime-sandbox-instead-7cf370226744?source=rss-d690390b08a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf370226744</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[George Karanikolas]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 15:18:31 GMT</pubDate>
            <atom:updated>2026-03-10T15:18:31.016Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to replace an ever-growing list of static previews with a single composable that lets you explore every configuration at runtime.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7EhhZwUYZcclbqdknDXzg.jpeg" /></figure><p>Every Compose developer hits this wall eventually. You start with one @Preview. Then one for dark mode. Then one for large fonts. Then one per locale. Before you know it, you&#39;re scrolling through two dozen nearly-identical functions just to check whether a button label wraps in German.</p><p>The real problem isn’t laziness — it’s that static previews <strong>don’t scale</strong>. Dark × 3 locales × 4 font scales × RTL is 24 permutations for a <em>single</em> screen. And your IDE renders all of them every build.</p><p>So I built PreviewSandbox. Instead of multiplying preview functions, you get an interactive control panel that lets you toggle every configuration axis at runtime — no rebuilds, no system-setting changes.</p><h3>What It Looks Like</h3><p>The API is intentionally minimal:</p><pre>@Preview<br>@Composable<br>private fun ScreenPreview() {<br>    PreviewSandbox(<br>        theme = { state, content -&gt;<br>            AppTheme(darkTheme = state.isDark) { content() }<br>        }<br>    ) {<br>        MyScreen()<br>    }<br>}</pre><p>That’s one preview. One function. A ⚙ icon appears at runtime and opens a control panel where you can toggle:</p><ul><li><strong>Dark / light</strong> theme</li><li><strong>Language</strong> — cycles through your supported locales</li><li><strong>Font scale</strong> — 1.0×, 1.3×, 1.5×, 1.8×, 2.0×</li><li><strong>RTL</strong> layout direction</li><li><strong>Background</strong> color</li><li><strong>Wallpaper</strong> (for transparent UIs like widgets or overlays)</li><li><strong>Dynamic Color</strong> (Material You)</li><li><strong>Bold text</strong></li><li><strong>High contrast</strong> mode</li></ul><p>The control panel only shows the toggles that are relevant to your app. Everything else stays out of the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woa8gEJasj-isnZwd4YzqA.gif" /></figure><p><em>Show, don’t just tell: A quick demo of real-time configuration switching.</em></p><h3>When and Where It Works</h3><blockquote><strong><em>Preview Pane &amp; Devices:</em></strong><em> Most capabilities (dark mode, font scale, RTL, backgrounds, dynamic color) work effortlessly in Android Studio’s </em><a href="https://developer.android.com/develop/ui/compose/tooling/previews#preview-interactions"><em>interactive preview mode</em></a><em> and on physical devices.</em></blockquote><blockquote><strong><em>Locale Is the Exception:</em></strong><em> Locale switching requires a full Android runtime (emulator or device) to execute </em><a href="https://developer.android.com/reference/android/content/Context#createConfigurationContext(android.content.res.Configuration"><em>createConfigurationContext()</em></a><em>). Inside the preview pane, the chip appears, but </em><em>stringResource() won&#39;t reflect the language change.</em></blockquote><p>Bottom line: Use the interactive preview pane for quick visual tweaks. Boot an emulator or real device for UI localization reviews.</p><h3>The Static Preview Experience</h3><p>One deliberate design detail: <strong>the control panel is completely invisible in a static preview.</strong></p><pre>var showControls by remember { mutableStateOf(false) }<br>LaunchedEffect(Unit) {<br>    delay(150)<br>    showControls = true<br>}</pre><p>LaunchedEffect never fires during static rendering — it requires an actual composition lifecycle. So in the static preview pane, you see nothing but your composable, rendered cleanly. The gear icon and control panel only appear once the preview is running interactively or on a device. No clutter, no overlapping UI in screenshot tests.</p><p>This also means static previews still work exactly as they always did. PreviewSandbox simply doesn&#39;t interfere.</p><h3>How the Overrides Work</h3><p>The sandbox uses <a href="https://developer.android.com/develop/ui/compose/compositionlocal">CompositionLocal</a> — no framework hacks, just the extension points Compose was designed to expose.</p><h3>Locale → Context Re-Creation</h3><p>stringResource() resolves strings through the Android Context. To redirect this at runtime, the sandbox creates a configuration context with the new locale:</p><pre>val localizedContext = remember(state.locale, configuration) {<br>    val locale = Locale.forLanguageTag(state.locale.tag)<br>    val newConfig = Configuration(configuration).apply {<br>        setLocales(LocaleList(locale))<br>        setLayoutDirection(locale)<br>    }<br>    context.createConfigurationContext(newConfig)<br>}</pre><pre>CompositionLocalProvider(<br>    LocalContext provides localizedContext,<br>    LocalConfiguration provides localizedContext.resources.configuration,<br>) {<br>    content()<br>}</pre><p>Because this is a real Context with a real Configuration, everything that depends on locale works correctly — strings, plurals, date formatters, and number formatters. Nothing is fake.</p><h3>Font Scale → Density Override</h3><p>Android’s accessibility font scaling lives inside the Density object. Overriding it is one line:</p><pre>CompositionLocalProvider(<br>    LocalDensity provides Density(<br>        density = LocalDensity.current.density,<br>        fontScale = state.fontScale,<br>    ),<br>) {<br>    content()<br>}</pre><p>Every sp-sized text inside the sandbox now renders at the selected scale — no system settings required.</p><h3>RTL → Layout Direction + Automatic Detection</h3><p>Layout direction is controlled by LocalLayoutDirection. The sandbox overrides it, but also automatically detects when the selected locale is inherently RTL, so you don&#39;t have to manually toggle the RTL chip when switching to Arabic:</p><pre>val isRtlLocale = remember(state.locale.tag) {<br>    Locale.forLanguageTag(state.locale.tag)<br>        .layoutDirection == View.LAYOUT_DIRECTION_RTL<br>}</pre><pre>CompositionLocalProvider(<br>    LocalLayoutDirection provides<br>        if (state.isRtl || isRtlLocale) LayoutDirection.Rtl<br>        else LayoutDirection.Ltr,<br>) {<br>    content()<br>}</pre><h3>Capability-Driven Setup</h3><p>The ThemeCapabilities data class declares what your theme actually supports. Only enabled capabilities appear as chips in the control panel:</p><pre>PreviewSandbox(<br>    capabilities = ThemeCapabilities(<br>        supportedLocales = persistentListOf(<br>            SandboxLocale(&quot;en&quot;, &quot;English&quot;),<br>            SandboxLocale(&quot;el&quot;, &quot;Greek&quot;),<br>            SandboxLocale(&quot;ar&quot;, &quot;Arabic&quot;),<br>        ),<br>        supportsRtl = true,<br>        supportsDynamicColor = true,<br>    ),<br>    theme = { state, content -&gt;<br>        AppTheme(<br>            darkTheme = state.isDark,<br>            dynamicColor = state.isDynamicColor,<br>        ) { content() }<br>    }<br>) {<br>    MyScreen()<br>}</pre><p>A utility app with no localization support would pass supportsLocale = false and never see a locale chip.</p><h3>A Few Design Choices Worth Noting</h3><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/Immutable"><strong>@Immutable</strong></a><strong> everywhere.</strong> Every data class — PreviewSandboxState, ThemeCapabilities, SandboxLocale, SandboxBackground — is annotated with @Immutable. This tells the Compose compiler that these objects won&#39;t change after creation, letting it skip recompositions of subtrees whose inputs haven&#39;t changed. When you&#39;re wrapping a full screen, this matters.</p><p><a href="https://github.com/Kotlin/kotlinx.collections.immutable"><strong>PersistentList</strong></a><strong> instead of </strong><strong>List.</strong> The compiler can&#39;t prove that a regular List won&#39;t be mutated at some point, so it conservatively marks it as unstable. PersistentList (from kotlinx-collections-immutable) is immutable by construction, which restores that stability guarantee.</p><p><strong>State survives rotation.</strong> The sandbox state is stored with <a href="https://developer.android.com/develop/ui/compose/state#restore-ui-state">rememberSaveable</a> and a custom listSaver that serializes booleans, strings, and floats into a flat list. If you rotate the device mid-test, you don&#39;t lose your selected configuration.</p><h3>Where It Actually Helps</h3><p><strong>Design reviews.</strong> Sit with a designer and cycle through configurations in real time. “Does this button truncate in German at large font?” — answered in two taps, not two builds.</p><p><strong>Transparent UI testing.</strong> The wallpaper capability lets you test widgets or overlays against different backgrounds — something genuinely annoying to set up with static previews.</p><p><strong>Accessibility audits.</strong> An external auditor can toggle large fonts, bold text, high contrast, and RTL independently, without touching system settings.</p><h3>Recommended Integration Pattern</h3><p>Define shared capabilities and a wrapper composable once in your design-system module:</p><pre>val AppPreviewCapabilities = ThemeCapabilities(<br>    supportedLocales = persistentListOf(<br>        SandboxLocale(&quot;en&quot;, &quot;English&quot;),<br>        SandboxLocale(&quot;de&quot;, &quot;German&quot;),<br>        SandboxLocale(&quot;ar&quot;, &quot;Arabic&quot;),<br>    ),<br>    supportsRtl = true,<br>    supportsDynamicColor = true,<br>)</pre><pre>@Composable<br>fun AppPreviewSandbox(content: @Composable () -&gt; Unit) {<br>    PreviewSandbox(<br>        capabilities = AppPreviewCapabilities,<br>        theme = { state, innerContent -&gt;<br>            AppTheme(<br>                darkTheme = state.isDark,<br>                dynamicColor = state.isDynamicColor,<br>                isBoldText = state.isBoldText,<br>                isHighContrast = state.isHighContrast,<br>            ) {<br>                innerContent()<br>            }<br>        },<br>        content = content,<br>    )<br>}</pre><p>Then every screen preview becomes:</p><pre>@Preview<br>@Composable<br>private fun HomeScreenPreview() {<br>    AppPreviewSandbox {<br>        HomeScreen(<br>            uiState = HomeUiState.Preview,<br>            onEvent = {},<br>        )<br>    }<br>}</pre><p>One function. All configurations. Clean static render. Full runtime control.</p><h3>Technical Requirements</h3><p>Before you drop this into your project, keep two things in mind:</p><ol><li><strong>Min SDK 24</strong>: The locale override implementation uses <a href="https://developer.android.com/reference/android/os/LocaleList">LocaleList</a>, which was introduced in Android 7.0 (API 24). If your app supports lower versions, you&#39;ll need to add a version check or use a fallback mechanism.</li><li><strong>External Dependencies</strong>: The code relies on <a href="https://github.com/Kotlin/kotlinx.collections.immutable">kotlinx-collections-immutable</a> for PersistentList. This is essential for ensuring that the ThemeCapabilities and PreviewSandboxState objects are treated as stable by the Compose compiler.</li></ol><h3>How It Compares to Multi-Preview Annotations</h3><p>Android Studio’s <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/tooling/preview/PreviewFontScale">@PreviewFontScale</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/tooling/preview/PreviewScreenSizes">@PreviewScreenSizes</a>, and custom <a href="https://developer.android.com/develop/ui/compose/tooling/previews#multipreview-annotations">multi-preview annotations</a> are incredibly useful, but they solve a different problem:</p><ul><li><strong>Build vs. Runtime:</strong> Static previews require a build; the sandbox applies combinations dynamically with zero build cost.</li><li><strong>Snapshots vs. Interactive:</strong> Multi-previews generate view-only snapshots. PreviewSandbox is a live playground.</li><li><strong>Automated vs. Manual:</strong> Static previews excel at CI screenshot tests. The sandbox enables hands-on QA and design reviews.</li></ul><p>They naturally complement each other.</p><h3>Closing Thoughts</h3><p>Static previews are perfect for fast, visual validation. But when you need cross-axis interactive exploration, QA handoffs, or edge-case testing, they fall short.</p><p>PreviewSandbox bridges this gap using CompositionLocal—no hacks, pure Compose semantics, and zero friction with your existing setup.</p><p>Grab the source code: 👉 <a href="https://github.com/SeijinD/PreviewSandbox"><strong>PreviewSandbox Repository</strong></a></p><p><em>Let’s connect!</em> Find me on <a href="https://github.com/SeijinD">GitHub</a> &amp; <a href="https://www.linkedin.com/in/seijind/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf370226744" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>