• Stars
    star
    1,710
  • Rank 26,170 (Top 0.6 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 3 years ago
  • Updated 20 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Build a StateFlow stream using Jetpack Compose

Molecule

Build a StateFlow or Flow stream using Jetpack Compose1.

fun CoroutineScope.launchCounter(): StateFlow<Int> = launchMolecule(clock = ContextClock) {
  var count by remember { mutableStateOf(0) }

  LaunchedEffect(Unit) {
    while (true) {
      delay(1_000)
      count++
    }
  }

  count
}

Introduction

Jetpack Compose UI makes it easy to build declarative UI with logic.

val userFlow = db.userObservable()
val balanceFlow = db.balanceObservable()

@Composable
fun Profile() {
  val user by userFlow.subscribeAsState(null)
  val balance by balanceFlow.subscribeAsState(0L)

  if (user == null) {
    Text("Loading…")
  } else {
    Text("${user.name} - $balance")
  }
}

Unfortunately, we are mixing business logic with display logic which makes testing harder than if it were separated. The display layer is also interacting directly with the storage layer which creates undesirable coupling. Additionally, if we want to power a different display with the same logic (potentially on another platform) we cannot.

Extracting the business logic to a presenter-like object fixes these three things.

In Cash App our presenter objects traditionally expose a single stream of display models through Kotlin coroutine's Flow or RxJava Observable.

sealed interface ProfileModel {
  object Loading : ProfileModel
  data class Data(
    val name: String,
    val balance: Long,
  ) : ProfileModel
}

class ProfilePresenter(
  private val db: Db,
) {
  fun transform(): Flow<ProfileModel> {
    return combine(
      db.users().onStart { emit(null) },
      db.balances().onStart { emit(0L) },
    ) { user, balance ->
      if (user == null) {
        Loading
      } else {
        Data(user.name, balance)
      }
    }
  }
}

This code is okay, but the ceremony of combining reactive streams will scale non-linearly. This means the more sources of data which are used and the more complex the logic the harder to understand the reactive code becomes.

Despite emitting the Loading state synchronously, Compose UI requires an initial value be specified for all Flow or Observable usage. This 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.

Molecule lets us fix both of these problems. Our presenter can return a StateFlow<ProfileModel> whose initial state can be read synchronously at the view layer by Compose UI. And 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.

@Composable
fun ProfilePresenter(
  userFlow: Flow<User>,
  balanceFlow: Flow<Long>,
): ProfileModel {
  val user by userFlow.collectAsState(null)
  val balance by balanceFlow.collectAsState(0L)

  return if (user == null) {
    Loading
  } else {
    Data(user.name, balance)
  }
}

This model-producing composable function can be run with launchMolecule.

val userFlow = db.users()
val balanceFlow = db.balances()
val models: StateFlow<ProfileModel> = scope.launchMolecule(clock = ContextClock) {
  ProfilePresenter(userFlow, balanceFlow)
}

A coroutine that runs ProfilePresenter and shares its output with the StateFlow is launched into the provided CoroutineScope.

At the view-layer, consuming the StateFlow of our model objects becomes trivial.

@Composable
fun Profile(models: StateFlow<ProfileModel>) {
  val model by models.collectAsState()
  when (model) {
    is Loading -> Text("Loading…")
    is Data -> Text("${model.name} - ${model.balance}")
  }
}

For more information see the launchMolecule documentation.

Flow

In addition to StateFlows, Molecule can create regular Flows.

Here is the presenter example updated to use a regular Flow:

val userFlow = db.users()
val balanceFlow = db.balances()
val models: Flow<ProfileModel> = moleculeFlow(clock = Immediate) {
  ProfilePresenter(userFlow, balanceFlow)
}

And the counter example:

fun counter(): Flow<Int> = moleculeFlow(clock = Immediate) {
  var count by remember { mutableStateOf(0) }

  LaunchedEffect(Unit) {
    while (true) {
      delay(1_000)
      count++
    }
  }

  count
}

For more information see the moleculeFlow documentation.

Usage

Add the buildscript dependency and apply the plugin to every module which wants to call launchMolecule or define @Composable functions for use with Molecule.

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'app.cash.molecule:molecule-gradle-plugin:0.9.0'
  }
}

apply plugin: 'app.cash.molecule'

Since Kotlin compiler plugins are an unstable API, certain versions of Molecule only work with certain versions of Kotlin.

Kotlin Molecule
1.8.20 0.9.0
1.8.10 0.8.0
1.8.0 0.7.0 - 0.7.1
1.7.20 0.6.0 - 0.6.1
1.7.10 0.4.0 - 0.5.0
1.7.0 0.3.0 - 0.3.1
1.6.10 0.2.0
1.5.31 0.1.0
Snapshots of the development version are available in Sonatype's snapshots repository.

buildscript {
  repositories {
    mavenCentral()
    maven {
      url 'https://oss.sonatype.org/content/repositories/snapshots/'
    }
  }
  dependencies {
    classpath 'app.cash.molecule:molecule-gradle-plugin:0.10.0-SNAPSHOT'
  }
}

apply plugin: 'app.cash.molecule'

Frame Clock

Whenever Jetpack Compose recomposes, it always waits for the next frame before beginning its work. It is dependent on a MonotonicFrameClock in its CoroutineContext to know when a new frame is sent. Molecule 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.

Unlike Jetpack Compose, however, Molecule will sometimes be run in circumstances that do not provide a MonotonicFrameClock. So all Molecule APIs require you to specify your preferred clock behavior:

  • RecompositionClock.ContextClock behaves like Jetpack Compose: it will fish the MonotonicFrameClock out of the calling coroutineContext and use it for recomposition. If there is no MonotonicFrameClock, it will throw an exception. ContextClock is useful with Android's AndroidUiDispatcher.Main. Main has a built-in MonotonicFrameClock that is synchronized with the frame rate of the device. So a Molecule run on Main with ContextClock will run in lock step with the frame rate, too. Nifty! You can also provide your own BroadcastFrameClock to implement your own frame rate.
  • RecompositionClock.Immediate will construct an immediate clock. This clock will produce a frame whenever the enclosing flow is ready to emit an item. (This is always the case for a StateFlow.) Immediate can be used where no clock is available at all without any additional wiring. It may be used for unit testing, or for running molecules off the main thread.

Testing

Use moleculeFlow(clock = Immediate) and test using Turbine. Your moleculeFlow will run just like any other flow does in Turbine.

@Test fun counter() = runTest {
  moleculeFlow(RecompositionClock.Immediate) {
    Counter()
  }.test {
    assertEquals(0, awaitItem())
    assertEquals(1, awaitItem())
    assertEquals(2, awaitItem())
    cancel()
  }
}

If you're unit testing Molecule on the JVM in an Android module, please set below in your project's AGP config.

android {
  ...
  testOptions {
    unitTests.returnDefaultValues = true
  }
  ...
}

License

Copyright 2021 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Footnotes

  1. …and NOT Jetpack Compose UI!

More Repositories

1

sqldelight

SQLDelight - Generates typesafe Kotlin APIs from SQL
Kotlin
5,918
star
2

turbine

A small testing library for kotlinx.coroutines Flow
Kotlin
2,323
star
3

paparazzi

Render your Android screens without a physical device or emulator
Kotlin
2,164
star
4

zipline

Run Kotlin/JS libraries in Kotlin/JVM and Kotlin/Native programs
C
1,914
star
5

contour

Layouts with lambdas 😎
Kotlin
1,522
star
6

redwood

Multiplatform reactive UI for Android, iOS, and web using Kotlin and Jetpack Compose
Kotlin
1,458
star
7

InflationInject

Constructor-inject views during XML layout inflation
Kotlin
908
star
8

pranadb

Go
615
star
9

licensee

Gradle plugin which validates the licenses of your dependency graph match what you expect
Kotlin
599
star
10

hermit

🐚 Hermit manages isolated, self-bootstrapping sets of tools in software projects.
Go
557
star
11

AccessibilitySnapshot

Easy regression testing for iOS accessibility
Swift
522
star
12

exhaustive

An annotation and Kotlin compiler plugin for enforcing a when statement is exhaustive
Kotlin
465
star
13

multiplatform-paging

A library that packages AndroidX Paging for Kotlin/Multiplatform.
Kotlin
452
star
14

misk

Microservice Kontainer
Kotlin
386
star
15

copper

A content provider wrapper for reactive queries
Kotlin
300
star
16

barber

Barber 💈 A type safe Kotlin JVM library for building up localized, fillable, themed documents using Mustache templating
Kotlin
157
star
17

paraphrase

A Gradle plugin that generates type-safe formatters for Android string resources in the ICU message format.
Kotlin
157
star
18

stagehand

Modern, type-safe API for building animations on iOS
Swift
126
star
19

hermit-packages

Hermit manages isolated, self-bootstrapping sets of tools in software projects.
HCL
111
star
20

quiver

Quiver is a collection of extension methods and handy functions to make the wonderful functional programming Kotlin library, Arrow, even better.
Kotlin
95
star
21

spirit

Online Schema Change Tool for MySQL 8.0
Go
87
star
22

pivit

Go
82
star
23

tempest

Typesafe DynamoDB for Kotlin and Java.
Kotlin
80
star
24

better-dynamic-features

Making dynamic feature modules better
Kotlin
70
star
25

misk-web

Micro-Frontends React + Redux + Typescript Framework
TypeScript
65
star
26

blip

Sublime MySQL monitoring
Go
59
star
27

logquacious

Logquacious (lq) is a fast and simple log viewer.
TypeScript
58
star
28

wisp

Wisp is a collection of kotlin modules providing various features and utilities, including config, logging, feature flags and more.
Kotlin
58
star
29

certifikit

Kotlin Certificate processing library.
Kotlin
40
star
30

backfila

Service that manages backfill state, calling into other services to do batched work
Kotlin
30
star
31

cash-app-pay-android-sdk

Cash Android PayKit SDK for merchant integrations with Cash App Pay
Kotlin
29
star
32

nostrino

A Kotlin SDK for Nostr
Kotlin
28
star
33

transflect

Kubernetes operator using Istio to set up Envoy's gRPC-JSON transcoding.
Go
24
star
34

cmmc

K8S ConfigMap Merging Controller
Go
20
star
35

cloner

Go
20
star
36

kfsm

Finite state machinery in Kotlin
Kotlin
19
star
37

yet-another-aws-exporter

A Prometheus metrics exporter for AWS that fills in gaps CloudWatch doesn't cover
Go
17
star
38

cash-app-pay-ios-sdk

Swift
14
star
39

protosync

ProtoSync synchronises remote .proto files to a local directory
Go
13
star
40

cash-pay-pay-sdk-android-sample-app

Cash App Pay Kit SDK Sample app for Android.
Kotlin
12
star
41

trifle

Security functionality for interoperability/interaction with core services.
Swift
11
star
42

AardvarkReveal

Generate and attach a Reveal file to your Aardvark bug reports
Swift
10
star
43

ln-invoice

Parse lightning network payment requests (invoices) in Kotlin.
Kotlin
10
star
44

kfactories

Set of factories and utils to create effective and lightweight property-based testing strategies.
Kotlin
9
star
45

jooq-encryption

Kotlin
9
star
46

hermit-ij-plugin

Kotlin
8
star
47

cash-app-pay-sdk-ios-sample-app

Swift
7
star
48

AardvarkCrashReport

AardvarkCrashReport makes it easy to provide high quality data about crashes in your bug reports
Swift
7
star
49

awsu

su for aws roles
Go
7
star
50

check-signature-action

Shell
6
star
51

csop

Go
6
star
52

activate-hermit

Github Action to activate a Hermit environment.
Shell
6
star
53

kruit

TypeScript
4
star
54

chronicler

Kotlin
3
star
55

hermit-build

Relocatable/static builds for Hermit packages
Makefile
3
star
56

s3-copy-gradle-plugin

1
star
57

.github

1
star
58

hermit-package-version

Shell
1
star
59

cash-app-pay-sandbox-releases

1
star