What is Molecule and how does it work?
trunkMolecule is a library that allows you to build StateFlow or Flow streams using Jetpack Compose logic without requiring a UI node tree. It glues Compose's state management to kotlinx.coroutines flows.
Instead of using complex reactive operators (like combine) to merge multiple data sources, you can write imperative @Composable functions that use Compose features like remember, LaunchedEffect, and collectAsState. Molecule then runs these composables and emits the resulting state as a stream.
@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)
}
}
// Run the presenter to get a StateFlow
val models: StateFlow<ProfileModel> = scope.launchMolecule(mode = ContextClock) {
ProfilePresenter(userFlow, balanceFlow)
}