Share
Embed
Building StateFlows with Jetpack Compose
Mohit S
September 02, 2022
Transcript
152 slides
-
Building State Flows with Compose • How to setup and
use Molecule -
Building State Flows with Compose • How to setup and
use Molecule • Design Patterns -
Building State Flows with Compose • How to setup and
use Molecule • Design Patterns • Testing with Molecule -
Building State Flows with Compose • How to setup and
use Molecule • Design Patterns • Testing with Molecule • Molecule Internals -
Compose • General purpose tool for managing tree of nodes.
Node can be anything -
Compose • Compose Runtime • Kotlin Complier Plugin • State
Snapshot System -
@Composable fun ProfileScreen() { val user by userFlow.subscribeAsState(null) val balance
by balanceFlow.subscribeAsState(0L) if (user == null) { Text("Loading…") } else { Text("${user.name} - $balance") } } -
@Composable fun ProfileScreen() { val user by userFlow.subscribeAsState(null) val balance
by balanceFlow.subscribeAsState(0L) if (user == null) { Text("Loading…") } else { Text("${user.name} - $balance") } } -
@Composable fun ProfileScreen() { val user by userFlow.subscribeAsState(null) val balance
by balanceFlow.subscribeAsState(0L) if (user == null) { Text("Loading…") } else { Text("${user.name} - $balance") } } Undesired coupling -
@Composable fun ProfileScreen() { val user by userFlow.subscribeAsState(null) val balance
by balanceFlow.subscribeAsState(0L) if (user == null) { Text("Loading…") } else { Text("${user.name} - $balance") } } Not Reusable -
class ProfilePresenter(val db: Db) { fun transform(events: Flow<Event>) : Flow<ProfileModel>
{ } } sealed interface ProfileModel { object Loading : ProfileModel data class Data( val name: String, val balance: Long, ): ProfileModel } -
class ProfilePresenter(val db: Db) { fun transform(events: Flow<Event>) : Flow<ProfileModel>
{ return combine( db.users().onStart { emit(null) }, db.balances().onStart { emit(0L) }, ) { user, balance -> } } } -
class ProfilePresenter(val db: Db) { fun transform(events: Flow<Event>) : Flow<ProfileModel>
{ return combine( db.users().onStart { emit(null) }, db.balances().onStart { emit(0L) }, ) { user, balance -> } } } Can get complex if we add more streams -
@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) } } -
@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) } } -
@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) } } -
val scope = CoroutineScope(Main) scope.launchMolecule( clock = RecompositionClock.ContextClock
) { ProfilePresenter(events, randomService) } -
val scope = CoroutineScope(Main) val models: StateFlow<ProfileModel> = scope.launchMolecule(
clock = RecompositionClock.ContextClock ) { ProfilePresenter(events, randomService) } -
val scope = CoroutineScope(Main) val models: StateFlow<ProfileModel> = scope.launchMolecule(
clock = RecompositionClock.ContextClock ) { ProfilePresenter(events, randomService) } -
val scope = CoroutineScope(Main) val models: StateFlow<ProfileModel> = scope.launchMolecule(
clock = RecompositionClock.ContextClock ) { ProfilePresenter(events, randomService) } -
val scope = CoroutineScope(Main) scope.launchMolecule( clock = RecompositionClock.ContextClock,
emitter = { value -> } ) { ProfilePresenter(events, randomService) } -
val scope = CoroutineScope(Main) scope.launchMolecule( clock = RecompositionClock.ContextClock,
emitter = { value -> } ) { ProfilePresenter(events, randomService) } Will not respect back-pressure -
val models: Flow<ProfileModel> = moleculeFlow( clock = RecompositionClock.ContextClock
) { ProfilePresenter(events, randomService) } -
val scope = CoroutineScope(Main) val models: StateFlow<ProfileModel> = scope.launchMolecule(
clock = RecompositionClock.ContextClock ) { ProfilePresenter(events, randomService) } Frame Clock -
Composable Wait for next frame Enter the composition Leave the
composition Monotonic Frame Clock -
Monotonic Frame Clock Pull Based System Pull Signal Choreographer
Performs Pull for UI -
val scope = CoroutineScope(Main) fun <T> CoroutineScope.launchMolecule( ...
) { with(this + clockContext) { // Pass context element to Recomposer } } -
interface MonotonicFrameClock : CoroutineContext.Element { suspend fun withFrameNanos(onFrame): R override
val key: CoroutineContext.Key <*> get() = Key companion object Key : CoroutineContext.Key<MonotonicFrameClock> } -
Context Clock • Use MonotonicFrameClock from calling Coroutine
Context • Use Molecule with built in Android Frame Clock -
fun <T> CoroutineScope.launchMolecule( ... ) { val clockContext = when
(clock) { RecompositionClock.ContextClock -> EmptyCoroutineContext RecompositionClock.Immediate -> GatedFrameClock(this) } ... } -
fun <T> CoroutineScope.launchMolecule( ... ) { val clockContext = when
(clock) { RecompositionClock.ContextClock -> EmptyCoroutineContext RecompositionClock.Immediate -> GatedFrameClock(this) } ... } -
val dispatcher = TestCoroutineDispatcher() val clock = BroadcastFrameClock() Frame
clock provided by Compose -
val dispatcher = TestCoroutineDispatcher() val clock = BroadcastFrameClock() val
scope = CoroutineScope(dispatcher + clock) -
var value = 0 scope.launchMolecule(RecompositionClock.ContextClock, { value = it
}) { var count by remember { mutableStateOf(0) } LaunchedEffect(Unit) { while (true) { delay(100) count ++ } } count } -
scope.launchMolecule( ... ) { var count by remember { mutableStateOf(0)
} LaunchedEffect(Unit) { while (true) { delay(100) count ++ } } count } -
scope.launchMolecule( ... ) { var count by remember { mutableStateOf(0)
} LaunchedEffect(Unit) { while (true) { delay(100) count ++ } } count } -
scope.launchMolecule(RecompositionClock.ContextClock) { var count by remember { mutableStateOf(0) } LaunchedEffect(Unit)
{ while (true) { delay(100) count ++ } } count } -
scope.launchMolecule(RecompositionClock.ContextClock) { var count by remember { mutableStateOf(0) } LaunchedEffect(Unit)
{ while (true) { delay(100) count ++ } } count } -
scope.launchMolecule(RecompositionClock.ContextClock) { var count by remember { mutableStateOf(0) } LaunchedEffect(Unit)
{ while (true) { delay(100) count ++ } } count } -
val dispatcher = TestCoroutineDispatcher() val clock = BroadcastFrameClock() val
scope = CoroutineScope(dispatcher + clock) -
Context Clock • Use MonotonicFrameClock from calling Coroutine
Context • Use Molecule with built in Android Frame Clock -
Gated Frame Clock • Request for a frame immediately succeeds
• Can be stopped -
Immediate class GatedFrameClock(scope: CoroutineScope) : MonotonicFrameClock { val frameSends
= Channel<Unit>(CONFLATED) init { scope.launch { for (send in frameSends) sendFrame() } } ... } -
Immediate class GatedFrameClock(scope: CoroutineScope) : MonotonicFrameClock { val clock
= BroadcastFrameClock { if (isRunning) frameSends.trySend(Unit).getOrThrow() } ... } -
val scope = CoroutineScope(Main) val models: StateFlow<ProfileModel> = scope.launchMolecule(
clock = RecompositionClock.ContextClock ) { ProfilePresenter(events, randomService) } -
Launching Molecules • Create coroutine scope • Specify frame clock
• Provide Composable function -
class ProfilePresenter(val repo: Repo): MoleculePresenter< ... > { @Composable override
fun models(events: Flow<ProfileEvent>): ProfileModel { } } -
@Composable fun models(events: Flow<ProfileEvent>): ProfileModel { var data by remember
{ mutableStateOf<ProfileData?>(null) } LaunchedEffect(Unit) { data = repo.getProfileData() } } -
@Composable fun models(events: Flow<ProfileEvent>): ProfileModel { ... return if
(data == null) { ProfileModel.Loading } else { ProfileModel.Success(data) } } -
@Composable fun models(events: Flow<ProfileEvent>): ProfileModel { LaunchedEffect(events) { events.collect {
when (it) { Events.Edit -> { ... } } } } } -
@Composable fun models(events: Flow<ProfileEvent>): ProfileModel { CollectEffect(events) { when (it)
{ Events.ClickedSubmit -> { ... } } } } -
class ProfilePresenter: MoleculePresenter<ProfileEvent, ProfileModel> { @Composable override fun models(events: Flow<ProfileEvent>):
ProfileModel { } } Can get complex -
class ProfilePresenter( val component1Presenter: Component1Presenter, ... ): MoleculePresenter
{ @Composable override fun models(events: Flow<ProfileEvent>): ProfileModel { } } -
class ProfilePresenter( ... ): MoleculePresenter { @Composable override fun models(events:
Flow<ProfileEvent>): ProfileModel { val model = component1Presenter.models(events) } } -
val models: StateFlow<ProfileModel> = scope.launchMolecule( clock = RecompositionClock.ContextClock
) { ProfilePresenter(randomService) } Testing -
Turbine • Queue based testing • Use to be an
extension in SQL Delight -
Turbine interface ReceiveTurbine<T> { fun awaitEvent(): Event<T> fun awaitError(): Throwable
suspend fun awaitItem(): T ... } -
Turbine flow { emit("one") emit("two") }.test { assertEquals("one", awaitItem())
assertEquals("two", awaitItem()) } -
Turbine flow { emit("one") emit("two") }.test { assertEquals("one", awaitItem())
assertEquals("two", awaitItem()) } -
Turbine suspend fun <T> Flow<T>.test( validate: suspend ReceiveTurbine<T>.() -> Unit,
) { coroutineScope { collectTurbineIn(this).apply { } } } -
Turbine fun <T> Flow<T>.collectTurbineIn(scope: CoroutineScope): Turbine<T> { lateinit var
channel: Channel<T> val job = scope.launch(start = UNDISPATCHED) { channel = collectIntoChannel(this) } return ChannelTurbine(channel, job) } -
Turbine fun <T> Flow<T>.collectTurbineIn(scope: CoroutineScope): Turbine<T> { lateinit var
channel: Channel<T> val job = scope.launch(start = UNDISPATCHED) { channel = collectIntoChannel(this) } return ChannelTurbine(channel, job) } -
Turbine fun <T> Flow<T>.collectTurbineIn(scope: CoroutineScope): Turbine<T> { lateinit var
channel: Channel<T> val job = scope.launch(start = UNDISPATCHED) { channel = collectIntoChannel(this) } return ChannelTurbine(channel, job) } -
Turbine class ChannelTurbine<T>( channel: Channel<T> = Channel(UNLIMITED) ) : Turbine<T>
{ suspend fun awaitItem(): T = channel.awaitItem() } -
Turbine val channel = Turbine<Int>() listOf(1, 2, 3).forEach { channel.add(it)
} channel.skipItems(2) assertEquals(3, channel.awaitItem()) -
val channel = Turbine<Int>() listOf(1, 2, 3).forEach { channel.add(it) }
channel.skipItems(2) assertEquals(3, channel.awaitItem()) Turbine -
Turbine val channel = Turbine<Int>() listOf(1, 2, 3).forEach { channel.add(it)
} channel.skipItems(2) assertEquals(3, channel.awaitItem()) -
val models: StateFlow<ProfileModel> = scope.launchMolecule( clock = RecompositionClock.ContextClock
) { profilePresenter.models(events) } Testing -
Testing Cases • Verify correct models are created • Verify
side effects from events -
Molecule Testing @Test fun `should get success model`() = runBlocking
{ launchMolecule(RecompositionClock.Immediate) { profilePresenter.models(events) }.test { } } -
Molecule Testing @Test fun `should get success model`() = runBlocking
{ launchMolecule(RecompositionClock.Immediate) { profilePresenter.models(events) }.test { assertEquals(ProfileModel.Loading, awaitItem()) ... } } -
Molecule Testing @Test fun `should get success model`() = runBlocking
{ val events = MutableSharedFlow<Events>() launchMolecule(RecompositionClock.Immediate) { profilePresenter.models(events) }.test { } } -
Molecule Testing @Test fun `should get success model`() = runBlocking
{ launchMolecule(RecompositionClock.Immediate) { profilePresenter.models(events) }.test { events.emit(EditProfile) } } -
Molecule Testing @Test fun `should get success model`() = runBlocking
{ launchMolecule(RecompositionClock.Immediate) { profilePresenter.models(events) }.test { events.emit(EditProfile) // Assertions } } -
val scope = CoroutineScope(Main) fun <T> CoroutineScope.launchMolecule( ...
) { // Setup Recomposer } -
Internals • Compose Compiler & Runtime • How Molecule hooks
into Compose Runtime -
Compose Internals class Foo { fun bar() { ...
} } Code Parsing Analysis & Resolve IR -
@Composable fun Greeting(name: String, $composer: Composer <*> ) { Text(name)
} Connects to Compose Runtime Compose Internals -
@Composable fun Greeting(name: String, $composer: Composer <*> ) { Text(name,
$composer) } Calling context is passed along Compose Internals -
@Composable inline fun Layout( ... ) { ReusableComposeNode<ComposeUiNode, Applier<Any
>> ( update = { set(measurePolicy, ComposeUiNode.SetMeasurePolicy) set(density, ComposeUiNode.SetDensity) ... }, ) } Composition Teaching the runtime -
@Composable inline fun ResuableComposeNode( ... ) { ... currentComposer.startReusableNode()
... currentComposer.createNode(factory) } Composition Delegate to composer -
Composition @Composable inline fun remember( ... ) { ...
currentComposer.cache( ... ) } -
@Composable inline fun ResuableComposeNode( ... ) { ... currentComposer.startReusableNode()
... currentComposer.createNode(factory) } Composition Changes List Change(…) Change(…) Change(…) -
Composition internal typealias Change = ( applier: Applier <*> ,
slots: SlotWriter, rememberManager: RememberManager ) -> Unit -
Composition class UiApplier(…): AbstractApplier { fun insertBottomUp( ... )
fun insertTopDown( ... ) fun move( ... ) fun onClear( ... ) fun onEndChanges( ... ) fun remove( ... ) } Applier in Compose UI -
Entry Points for Client Libraries • Create a recomposer •
Specify Applier • Call setContent with composable function -
val contextWithClock = currentThreadContext + (pausableClock ?: EmptyCoroutineContext)
val recomposer = Recomposer(contextWithClock) Compose UI Example -
fun launchMolecule(clock: RecompositionClock, body: @Composable () -> T) { with(this
+ clockContext) { val recomposer = Recomposer(coroutineContext) val composition = Composition(UnitApplier, recomposer) launch(start = UNDISPATCHED) { recomposer.runRecomposeAndApplyChanges() } } } Molecule Internals -
fun launchMolecule( ... ) { with(this + clockContext) { val
recomposer = Recomposer(coroutineContext) val composition = Composition(UnitApplier, recomposer) launch(start = UNDISPATCHED) { recomposer.runRecomposeAndApplyChanges() } } } Molecule Internals -
Recomposer • Creates coroutine Job • Applies changes for recomposition
using context • Cancels composition or recompositions when shutdown -
fun launchMolecule( ... ) { with(this + clockContext) { val
recomposer = Recomposer(coroutineContext) val composition = Composition(UnitApplier, recomposer) launch(start = UNDISPATCHED) { recomposer.runRecomposeAndApplyChanges() } } } Molecule Internals -
fun launchMolecule(@Composable body: () -> T) { with(this + clockContext)
{ ... composition.setContent { body() } } } Molecule Internals -
fun launchMolecule(emitter: (value: T) -> Unit) { with(this + clockContext)
{ ... composition.setContent { emitter(body()) } } } Molecule Internals -
Molecule Internals var flow: MutableStateFlow<T>? = null launchMolecule( emitter =
{ value -> outputFlow.value = value }, ... ) -
Building State Flows with Compose • How to setup and
use Molecule • Design Patterns • Testing with Molecule • Molecule Internals