Molecule: Build a StateFlow stream using Jetpack Compose
Article Summary
Cash App open sourced Molecule, a library that lets you write reactive code as simple if/else statements. No more complex RxJava chains.
Benoît Quenaudon from Cash App explains how Molecule bridges Jetpack Compose's reactive runtime with traditional Kotlin flows and StateFlows. The library hit version 0.4.0 and is now running in production at Cash App.
Key Takeaways
- Molecule transforms any @Composable function into a Flow or StateFlow
- Write presenters using if/else and when statements instead of chained operators
- Two recomposition clocks: ContextClock for frame-based, Immediate for eager updates
- Cash App now writes all new presenters as composable methods
- Simpler to write, review, and test than traditional reactive patterns
Molecule lets Android developers write reactive state management code imperatively using Compose's runtime, eliminating complex operator chains while maintaining full reactiveness.
About This Article
Android developers struggled to use Jetpack Compose's reactive runtime outside of composable functions. They had to write complex workarounds to connect composable methods with traditional Kotlin flows and StateFlows.
Cash App built the Molecule library to convert @Composable functions into Flow or StateFlow. The moleculeFlow() and launchMolecule() APIs handle this conversion. It supports two recomposition clocks: ContextClock for frame-based updates and Immediate for eager emission.
Molecule reached version 0.4.0 and went into production at Cash App. Presenters written as composable methods are now simpler to write, review, and test compared to traditional reactive patterns.