[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-7505":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":17,"stars30d":18,"stars90d":16,"forks30d":16,"starsTrendScore":19,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":21,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":22,"hasPages":24,"topics":25,"createdAt":10,"pushedAt":10,"updatedAt":26,"readmeContent":27,"aiSummary":28,"trendingCount":16,"starSnapshotCount":16,"syncStatus":29,"lastSyncTime":30,"discoverSource":31},7505,"molecule","cashapp\u002Fmolecule","cashapp","Build a StateFlow stream using Jetpack Compose","https:\u002F\u002Fcashapp.github.io\u002Fmolecule\u002Fdocs\u002F2.x\u002F",null,"Kotlin",2200,109,31,24,0,1,12,3,28.12,"Apache License 2.0",false,"trunk",true,[],"2026-06-12 02:01:40","# Molecule\n\nBuild a `StateFlow` or `Flow` stream using Jetpack Compose[^1].\n\n```kotlin\nfun CoroutineScope.launchCounter(): StateFlow\u003CInt> = launchMolecule(mode = ContextClock) {\n  var count by remember { mutableStateOf(0) }\n\n  LaunchedEffect(Unit) {\n    while (true) {\n      delay(1_000)\n      count++\n    }\n  }\n\n  count\n}\n```\n\nWait–I thought Jetpack Compose was a UI toolkit for Android?\n\nCompose is, at its core, a general-purpose compiler and runtime to do state tracking and tree node and property manipulation.\nThis can be used on any platform supported by Kotlin for any kind of state or with any tree.\nIt's an amazing piece of technology.\n\nMolecule \"just\" glues Compose's state management to kotlinx.coroutines' flows so that it can be used without the node tree.\n\n![molecule is not a framework, just a headless compose ui meme](.\u002Fmolecule_not_a_framework_sign.jpg)\n\n[^1]: …and NOT Jetpack Compose UI!\n\n\n## Introduction\n\nJetpack Compose UI makes it easy to build declarative UI with logic.\n\n```kotlin\nval userFlow = db.userObservable()\nval balanceFlow = db.balanceObservable()\n\n@Composable\nfun Profile() {\n  val user by userFlow.subscribeAsState(null)\n  val balance by balanceFlow.subscribeAsState(0L)\n\n  if (user == null) {\n    Text(\"Loading…\")\n  } else {\n    Text(\"${user.name} - $balance\")\n  }\n}\n```\n\nUnfortunately, we are mixing business logic with display logic which makes testing harder than if it were separated.\nThe display layer is also interacting directly with the storage layer which creates undesirable coupling.\nAdditionally, if we want to power a different display with the same logic (potentially on another platform) we cannot.\n\nExtracting the business logic to a presenter-like object fixes these three things.\n\nIn Cash App our presenter objects traditionally expose a single stream of display models through Kotlin coroutine's `Flow` or RxJava `Observable`.\n\n```kotlin\nsealed interface ProfileModel {\n  object Loading : ProfileModel\n  data class Data(\n    val name: String,\n    val balance: Long,\n  ) : ProfileModel\n}\n\nclass ProfilePresenter(\n  private val db: Db,\n) {\n  fun transform(): Flow\u003CProfileModel> {\n    return combine(\n      db.users().onStart { emit(null) },\n      db.balances().onStart { emit(0L) },\n    ) { user, balance ->\n      if (user == null) {\n        Loading\n      } else {\n        Data(user.name, balance)\n      }\n    }\n  }\n}\n```\n\nThis code is okay, but the ceremony of combining reactive streams will scale non-linearly.\nThis means the more sources of data which are used and the more complex the logic the harder to understand the reactive code becomes.\n\nDespite emitting the `Loading` state synchronously, Compose UI [requires an initial value](https:\u002F\u002Fdeveloper.android.com\u002Freference\u002Fkotlin\u002Fandroidx\u002Fcompose\u002Fruntime\u002Fpackage-summary#(kotlinx.coroutines.flow.Flow).collectAsState(kotlin.Any,kotlin.coroutines.CoroutineContext)) be specified for all `Flow` or `Observable` usage.\nThis is a layering violation as the view layer is not in the position to dictate a reasonable default since the presenter layer controls the model object.\n\nMolecule lets us fix both of these problems.\nOur presenter can return a `StateFlow\u003CProfileModel>` whose initial state can be read synchronously at the view layer by Compose UI.\nAnd by using Compose we also can build our model objects using imperative code built on features of the Kotlin language rather than reactive code consisting of RxJava library APIs.\n\n```kotlin\n@Composable\nfun ProfilePresenter(\n  userFlow: Flow\u003CUser>,\n  balanceFlow: Flow\u003CLong>,\n): ProfileModel {\n  val user by userFlow.collectAsState(null)\n  val balance by balanceFlow.collectAsState(0L)\n\n  return if (user == null) {\n    Loading\n  } else {\n    Data(user.name, balance)\n  }\n}\n```\n\nThis model-producing composable function can be run with `launchMolecule`.\n\n```kotlin\nval userFlow = db.users()\nval balanceFlow = db.balances()\nval models: StateFlow\u003CProfileModel> = scope.launchMolecule(mode = ContextClock) {\n  ProfilePresenter(userFlow, balanceFlow)\n}\n```\n\nA coroutine that runs `ProfilePresenter` and shares its output with the `StateFlow` is launched into the provided `CoroutineScope`.\n\nAt the view-layer, consuming the `StateFlow` of our model objects becomes trivial.\n\n```kotlin\n@Composable\nfun Profile(models: StateFlow\u003CProfileModel>) {\n  val model by models.collectAsState()\n  when (model) {\n    is Loading -> Text(\"Loading…\")\n    is Data -> Text(\"${model.name} - ${model.balance}\")\n  }\n}\n```\n\nFor more information see [the `launchMolecule` documentation](https:\u002F\u002Fcashapp.github.io\u002Fmolecule\u002Fdocs\u002Flatest\u002Fmolecule-runtime\u002Fapp.cash.molecule\u002Flaunch-molecule.html).\n\n### Flow\n\nIn addition to `StateFlow`s, Molecule can create regular `Flow`s.\n\nHere is the presenter example updated to use a regular `Flow`:\n```kotlin\nval userFlow = db.users()\nval balanceFlow = db.balances()\nval models: Flow\u003CProfileModel> = moleculeFlow(mode = Immediate) {\n  ProfilePresenter(userFlow, balanceFlow)\n}\n```\n\nAnd the counter example:\n```kotlin\nfun counter(): Flow\u003CInt> = moleculeFlow(mode = Immediate) {\n  var count by remember { mutableStateOf(0) }\n\n  LaunchedEffect(Unit) {\n    while (true) {\n      delay(1_000)\n      count++\n    }\n  }\n\n  count\n}\n```\n\nFor more information see [the `moleculeFlow` documentation](https:\u002F\u002Fcashapp.github.io\u002Fmolecule\u002Fdocs\u002Flatest\u002Fmolecule-runtime\u002Fapp.cash.molecule\u002Fmolecule-flow.html).\n\n## Usage\n\nMolecule is a library for Compose, and it relies on JetBrains' Kotlin Compose plugin to be present for use.\nAny module which wants to call `launchMolecule` or define `@Composable` functions for use with Molecule must have this plugin applied.\nFor more information, see [the JetBrains Compose compiler documentation](https:\u002F\u002Fwww.jetbrains.com\u002Fhelp\u002Fkotlin-multiplatform-dev\u002Fcompose-compiler.html).\n\nMolecule itself can then be added like any other dependency:\n\n```groovy\ndependencies {\n  implementation(\"app.cash.molecule:molecule-runtime:2.2.0\")\n}\n```\n\n\u003Cdetails>\n\u003Csummary>Snapshots of the development version are available in the Central Portal Snapshots repository.\u003C\u002Fsummary>\n\u003Cp>\n\n```groovy\nrepositories {\n  mavenCentral()\n  maven {\n    url \"https:\u002F\u002Fcentral.sonatype.com\u002Frepository\u002Fmaven-snapshots\u002F\"\n  }\n}\n\ndependencies {\n  implementation(\"app.cash.molecule:molecule-runtime:2.3.0-SNAPSHOT\")\n}\n```\n\n\u003C\u002Fp>\n\u003C\u002Fdetails>\n\n### Frame Clock\n\nWhenever Jetpack Compose recomposes, it always waits for the next frame before beginning its work.\nIt is dependent on a `MonotonicFrameClock` in its `CoroutineContext` to know when a new frame is sent.\nMolecule is just Jetpack Compose under the hood, so it also requires a frame clock: values won't be produced until a frame is sent and recomposition occurs.\n\nUnlike Jetpack Compose, however, Molecule will sometimes be run in circumstances that do not provide a `MonotonicFrameClock`.\nSo all Molecule APIs require you to specify your preferred clock behavior:\n\n* `RecompositionMode.ContextClock` behaves like Jetpack Compose: it will fish the `MonotonicFrameClock` out of the calling `coroutineContext` and use it for recomposition.\n  If there is no `MonotonicFrameClock`, it will throw an exception.\n  `ContextClock` is useful with Android's [`AndroidUiDispatcher.Main`](https:\u002F\u002Fcashapp.github.io\u002Fmolecule\u002Fdocs\u002Flatest\u002Fmolecule-runtime\u002Fapp.cash.molecule\u002F-android-ui-dispatcher\u002F-companion\u002F-main.html).\n  `Main` has a built-in `MonotonicFrameClock` that is synchronized with the frame rate of the device.\n  So a Molecule run on `Main` with `ContextClock` will run in lock step with the frame rate, too.\n  Nifty!\n  You can also provide your own `BroadcastFrameClock` to implement your own frame rate.\n* `RecompositionMode.Immediate` will construct an immediate clock.\n  This clock will produce a frame whenever the enclosing flow is ready to emit an item.\n  (This is always the case for a `StateFlow`.)\n  `Immediate` can be used where no clock is available at all without any additional wiring.\n  It may be used for unit testing, or for running molecules off the main thread.\n\n### Testing\n\nUse `moleculeFlow(mode = Immediate)` and test using [Turbine](https:\u002F\u002Fgithub.com\u002Fcashapp\u002Fturbine\u002F). Your `moleculeFlow` will run just like any other flow does in Turbine.\n\n```kotlin\n@Test fun counter() = runTest {\n  moleculeFlow(RecompositionMode.Immediate) {\n    Counter()\n  }.test {\n    assertEquals(0, awaitItem())\n    assertEquals(1, awaitItem())\n    assertEquals(2, awaitItem())\n    cancel()\n  }\n}\n```\n\n\nIf you're unit testing Molecule on the JVM in an Android module, please set below in your project's AGP config.\n\n```gradle\nandroid {\n  ...\n  testOptions {\n    unitTests.returnDefaultValues = true\n  }\n  ...\n}\n```\n\n\n## License\n\n    Copyright 2021 Square, Inc.\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http:\u002F\u002Fwww.apache.org\u002Flicenses\u002FLICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n","Molecule 是一个使用 Jetpack Compose 构建 `StateFlow` 或 `Flow` 数据流的库。它通过将 Compose 的状态管理与 kotlinx.coroutines 的流结合起来，使得开发者可以在没有 UI 树的情况下使用这些功能。核心特点包括简洁的状态管理和数据流处理，以及与 Kotlin 协程的良好集成。适合需要在非UI层进行复杂状态管理和数据流处理的应用场景，特别是在希望将业务逻辑与展示逻辑分离时。此外，Molecule 也适用于跨平台项目中保持一致的业务逻辑实现。",2,"2026-06-11 03:12:47","top_language"]