Share
Embed
Composing an API the *right* way (Droidcon Berlin 2024)
Everyone who writes code using Jetpack Compose designs Composable functions and components all the time. In this talk, we’ll take a look at some highlights from the official guidelines around designing Compose APIs, to see how we can do a better job of building with Compose.
More: https://zsmb.co/talks/composing-an-api-the-right-way/
Márton Braun
July 04, 2024
Transcript
144 slides
-
Agenda › Naming › Parameters › Default values › Modifiers
› Slots › State handling -
Constants const val DefaultKeyName = "__defaultKey" val StructurallyEqual: ComparisonPolicy =
StructurallyEqualsImpl() -
Constants const val DefaultKeyName = "__defaultKey" val StructurallyEqual: ComparisonPolicy =
StructurallyEqualsImpl() object ReferenceEqual : ComparisonPolicy {} sealed class LoadResult<T> { object Loading : LoadResult<Nothing>() class Done<T>(val result: T) : LoadResult<T>() class Error(val cause: Throwable) : LoadResult<Nothing>() } -
Constants const val DefaultKeyName = "__defaultKey" val StructurallyEqual: ComparisonPolicy =
StructurallyEqualsImpl() object ReferenceEqual : ComparisonPolicy {} sealed class LoadResult<T> { object Loading : LoadResult<Nothing>() class Done<T>(val result: T) : LoadResult<T>() class Error(val cause: Throwable) : LoadResult<Nothing>() } enum class Status { Idle, Busy, } -
Functions Return a value Emit content @Composable fun Column(...) @Composable
fun LaunchedEffect(...) @Composable fun Button(...) -
Functions Return a value @Composable fun stringResource( @StringRes id: Int
): String @Composable fun rememberScrollState( initial: Int = 0 ): ScrollState Emit content @Composable fun Column(...) @Composable fun LaunchedEffect(...) @Composable fun Button(...) -
Functions @Composable fun ColorScheme(darkTheme: Boolean): ColorScheme @Composable fun colorScheme(darkTheme: Boolean):
ColorScheme @Composable fun rememberCoroutineScope(): CoroutineScope @Composable fun CoroutineScope(): CoroutineScope -
Component /kəmˈpəʊnənt/ noun a @Composable function that returns Unit and
emits exactly one Compose UI tree node. -
Component /kəmˈpəʊnənt/ noun a @Composable function that returns Unit and
emits exactly one Compose UI tree node. -
Components @Composable fun Header() { Column { Text("Kotlin programming language")
Text("Concise. Cross-platform. Fun.") Row { Button { Text("Docs") } Button { Text("Blog") } } } } -
Components @Composable fun Header() { Column { Text("Kotlin programming language")
Text("Concise. Cross-platform. Fun.") Row { Button { Text("Docs") } Button { Text("Blog") } } } } -
Components @Composable fun Header() { Column { Row { Button
{ Text("Docs") } Button { Text("Blog") } } } } Text("Kotlin programming language") Text("Concise. Cross-platform. Fun.") -
Text("Kotlin programming language") Text("Concise. Cross-platform. Fun.") @Composable fun Title() {
} Components @Composable fun Header() { Column { Row { Button { Text("Docs") } Button { Text("Blog") } } } } -
Components Text("Kotlin programming language") Text("Concise. Cross-platform. Fun.") @Composable fun Title()
{ } @Composable fun Header() { Column { Title() Row { Button { Text("Docs") } Button { Text("Blog") } } } } -
Components Text("Kotlin programming language") Text("Concise. Cross-platform. Fun.") @Composable fun Title()
{ } @Composable fun Header() { Column { Title() Row { Button { Text("Docs") } Button { Text("Blog") } } } } -
Components Kotlin programming language Concise. Cross-platform. Fun. Text("Kotlin programming language")
Text("Concise. Cross-platform. Fun.") @Composable fun Title() { } -
Components Kotlin programming language Concise. Cross-platform. Fun. Text("Kotlin programming language")
Text("Concise. Cross-platform. Fun.") @Composable fun Title() { Column { } } -
Components Concise. Cross-platform. Fun. Kotlin programming language Text("Kotlin programming language")
Text("Concise. Cross-platform. Fun.") @Composable fun Title() { Column { } } -
Component /kəmˈpəʊnənt/ noun a @Composable function that returns Unit and
emits exactly one Compose UI tree node. -
Component /kəmˈpəʊnənt/ noun a @Composable function that returns Unit and
emits exactly one Compose UI tree node. -
Components @Composable fun InputField : { // ... } val
inputState = InputField Button(onClick = { inputState.value = "" }) { Text("Clear input") } UserInputState () () -
Components @Composable fun InputField : { // ... } Button(onClick
= { inputState.value = "" }) { Text("Clear input") } InputField UserInputState val inputState = () () -
Components @Composable fun InputField : UserInputState { // ... }
InputField () () Button(onClick = { inputState.value = "" }) { Text("Clear input") } val inputState = -
Components @Composable fun InputField inputState: { // ... } remember
{ UserInputState() } InputField inputState UserInputState val inputState = ( ) ( ) Button(onClick = { inputState.value = "" }) { Text("Clear input") } -
Components @Composable fun InputField(inputState: UserInputState) { // ... } val
inputState = remember { UserInputState() } InputField(inputState) Button(onClick = { inputState.value = "" }) { Text("Clear input") } -
Components @Composable fun InputField(inputState: UserInputState) { // ... } val
inputState = remember { UserInputState() } InputField(inputState) Button(onClick = { inputState.value = "" }) { Text("Clear input") } -
Components @Composable fun InputField(inputState: UserInputState) { // ... } val
inputState = remember { UserInputState() } Button(onClick = { inputState.value = "" }) { Text("Clear input") } InputField(inputState) -
Default arguments @Composable fun Text( text: String, modifier: Modifier =
Modifier, color: Color = Color.Unspecified, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current, ) -
Default arguments @Composable fun Text( text: String, modifier: Modifier =
Modifier, color: Color = Color.Unspecified, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current, ) -
@Composable fun Text( text: String, modifier: Modifier = Modifier, color:
Color = Color.Unspecified, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current, Default arguments ) -
Default arguments @Composable fun Text( text: String, modifier: Modifier =
Modifier, color: Color = Color.Unspecified, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle? = null, val actualStyle = style ?: LocalTextStyle.current // ... } ) { -
Default arguments @Composable fun Button( onClick: () -> Unit, modifier:
Modifier = Modifier, enabled: Boolean = true, shape: Shape = ButtonDefaults.shape, colors: ButtonColors = ButtonDefaults.buttonColors(), elevation: ButtonElevation? = ButtonDefaults.buttonElevation(), border: BorderStroke? = null, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit, ) -
Default arguments @Composable fun Button( onClick: () -> Unit, modifier:
Modifier = Modifier, enabled: Boolean = true, shape: Shape = ButtonDefaults.shape, colors: ButtonColors = ButtonDefaults.buttonColors(), elevation: ButtonElevation? = ButtonDefaults.buttonElevation(), border: BorderStroke? = null, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit, ) -
Default arguments object ButtonDefaults { val ContentPadding: PaddingValues val MinWidth:
Dp val MinHeight: Dp val IconSize: Dp val IconSpacing: Dp val shape: Shape @Composable get @Composable fun buttonElevation(...): ButtonElevation = ButtonElevation(...) } @Composable fun buttonColors(...): ButtonColors = ButtonColors(...) Button( onClick = { viewModel.savePage() }, colors = customColors ?: ButtonDefaults.buttonColors(), -
Default arguments object ButtonDefaults { } @Composable fun buttonColors(...): ButtonColors
= ButtonColors(...) Button( onClick = { viewModel.savePage() }, colors = customColors ?: ButtonDefaults.buttonColors(), ) { Text("Save") } -
Default arguments internal object ButtonDefaults { @Composable fun buttonColors(...): ButtonColors
= ButtonColors(...) } Button( onClick = { viewModel.savePage() }, colors = customColors ?: ButtonDefaults.buttonColors(), ) { Text("Save") } -
modifier: Modifier = Modifier, Modifiers PageTitle( text = "Home", modifier
= Modifier .width(100.dp) .height(40.dp) .background(Color.LightGray) .padding(horizontal = 12.dp) ) @Composable fun PageTitle( text: String, ) -
modifier: Modifier = Modifier, Modifiers PageTitle( text = "Home", modifier
= Modifier .width(100.dp) .height(40.dp) .background(Color.LightGray) .padding(horizontal = 12.dp) ) padding: Dp = 0.dp, @Composable fun PageTitle( text: String, ) -
Modifiers @Composable fun PageTitle( text: String, ) Box( Modifier .padding(12.dp)
.background(Color.Blue) ) { PageTitle("Home") } -
Modifiers @Composable fun PageTitle( text: String, ) Box( Modifier .padding(12.dp)
.background(Color.Blue) ) { PageTitle("Home") } @Composable fun PageTitle( text: String, modifier: Modifier = Modifier, ) PageTitle( "Home", Modifier .padding(12.dp) .background(Color.Blue), ) -
Modifiers › Accept a Modifier parameter › Named modifier ›
First optional parameter -
Modifiers › Accept a Modifier parameter › Named modifier ›
First optional parameter › Applied to the root node -
Modifiers › Accept a Modifier parameter › Named modifier ›
First optional parameter › Applied to the root node › Default value Modifier -
Modifiers › Accept a Modifier parameter › Named modifier ›
First optional parameter › Applied to the root node › Default value Modifier -
Modifiers › Accept a Modifier parameter › Named modifier ›
First optional parameter › Applied to the root node › Default value Modifier -
Modifiers › Accept a Modifier parameter › Named modifier ›
First optional parameter › Applied to the root node › Default value Modifier -
(modifier) (modifier) Modifiers @Composable fun Header( modifier: Modifier = Modifier,
) { Column Title() Row Button(onClick = { ... }) { Text("Docs") } Button(onClick = { ... }) { Text("Blog") } } } } { { -
(modifier) (modifier) Modifiers @Composable fun Header( modifier: Modifier = Modifier,
) { Column Title() Row Button(onClick = { ... }) { Text("Docs") } Button(onClick = { ... }) { Text("Blog") } } } } { { -
(modifier) (modifier) Modifiers @Composable fun Header( modifier: Modifier = Modifier,
) { Column Title() Row Button(onClick = { ... }) { Text("Docs") } Button(onClick = { ... }) { Text("Blog") } } } } { { -
Modifiers @Composable fun MenuItems( smallScreen: Boolean, modifier: Modifier = Modifier,
) { if (smallScreen) { Column(modifier) { Text(...) Text(...) } } else { Row(modifier) { Text(...) Text(...) } } } -
Modifiers › Accept a Modifier parameter › Named modifier ›
First optional parameter › Applied to the root node › Default value Modifier -
Modifiers modifier: Modifier = Modifier interface Modifier { infix fun
then(other: Modifier): Modifier = CombinedModifier(this, other) companion object : Modifier { ... override infix fun then(other: Modifier): Modifier = other override fun toString() = "Modifier" } } -
Modifiers @Composable fun Topics( topic: List<Topic>, modifier: Modifier = Modifier,
) { Row( modifier = modifier ) { // ... } } .padding(12.dp), -
Modifiers @Composable fun Topics( topic: List<Topic>, modifier: Modifier = Modifier,
) { Row( modifier = Modifier .then(modifier) ) { // ... } } .padding(12.dp) , -
Slots @Composable fun Button( content: @Composable , ) Button {
} } () -> Unit Row { ) ) Icon(Icons.Default.Build, "Build" Text("Build project" this: RowScope -
Slots @Composable fun Button( content: @Composable RowScope. , ) {
content() } } Button { } this: RowScope () -> Unit Row { ) ) Icon(Icons.Default.Build, "Build" Text("Build project" -
Slots @Composable fun Button( content: @Composable RowScope. , ) {
content() } } Button { } this: RowScope () -> Unit Row { ) ) Icon(Icons.Default.Build, "Build" Text("Build project" -
Slots Button { , Modifier.weight(1f) , Modifier.weight(4f) } this: RowScope
) ) @Composable fun Button( content: @Composable RowScope. , ) { content() } } () -> Unit Row { Icon(Icons.Default.Build, "Build" Text("Build project" -
Slots @Composable fun Button( content: @Composable RowScope.() -> Unit, )
{ Row { content() } } Button { , Modifier.weight(1f)) , Modifier.weight(4f)) } this: RowScope Icon(Icons.Default.Build, "Build" Text("Build project" -
Slot lifecycle @Composable fun PreferenceItem( checked: Boolean, content: @Composable ()
-> Unit, ) { if (checked) { Row { Text("Checked") content() } } else { Column { Text("Unchecked") content() } } } -
Slot lifecycle @Composable fun PreferenceItem( checked: Boolean, content: @Composable ()
-> Unit, ) { if (checked) { Row { Text("Checked") content() } } else { Column { Text("Unchecked") content() } } } -
Slot lifecycle @Composable fun PreferenceItem( checked: Boolean, content: @Composable ()
-> Unit, ) { if (checked) { Row { Text("Checked") content() } } else { Column { Text("Unchecked") content() } } } PreferenceItem -
Slot lifecycle @Composable fun PreferenceItem( checked: Boolean, content: @Composable ()
-> Unit, ) { if (checked) { Row { Text("Checked") content() } } else { Column { Text("Unchecked") content() } } } PreferenceItem content -
Slot lifecycle val movableContent = remember(content) { movableContentOf(content) } @Composable
fun PreferenceItem( checked: Boolean, content: @Composable () -> Unit, ) { if (checked) { Row { Text("Checked") content() } } else { Column { Text("Unchecked") content() } } } checked = false checked = true checked = false PreferenceItem content -
Slot lifecycle @Composable fun PreferenceItem( checked: Boolean, content: @Composable ()
-> Unit, ) { if (checked) { Row { Text("Checked") movableContent() } } else { Column { Text("Unchecked") movableContent() } } } val movableContent = remember(content) { movableContentOf(content) } -
Slot lifecycle @Composable fun PreferenceItem( checked: Boolean, content: @Composable ()
-> Unit, ) { val movableContent = remember(content) { movableContentOf(content) } if (checked) { Row { Text("Checked") movableContent() } } else { Column { Text("Unchecked") movableContent() } } } jb.gg/movable-content-of -
Ordering parameters › Required parameters › Optional parameters › First
one: Modifier › Trailing content lambda -
Ordering parameters fun NiaTopicTag( modifier: Modifier = Modifier, followed: Boolean,
onClick: () -> Unit, enabled: Boolean = true, text: @Composable () -> Unit, ) › Required parameters › Optional parameters › First one: Modifier › Trailing content lambda @Composable -
Ordering parameters › Required parameters › Optional parameters › First
one: Modifier › Trailing content lambda fun NiaTopicTag( modifier: Modifier = Modifier, followed: Boolean, onClick: () -> Unit, enabled: Boolean = true, text: @Composable () -> Unit, ) @Composable -
Ordering parameters NiaTopicTag(true, { toggleFollowed(id) }) { Text("Compose") } ›
Required parameters › Optional parameters › First one: Modifier › Trailing content lambda fun NiaTopicTag( modifier: Modifier = Modifier, followed: Boolean, onClick: () -> Unit, enabled: Boolean = true, text: @Composable () -> Unit, ) @Composable -
Ordering parameters NiaTopicTag(true, { toggleFollowed(id) } Text("Compose") } › Required
parameters › Optional parameters › First one: Modifier › Trailing content lambda fun NiaTopicTag( modifier: Modifier = Modifier, followed: Boolean, onClick: () -> Unit, enabled: Boolean = true, text: @Composable () -> Unit, ) ) { @Composable -
Ordering parameters NiaTopicTag(true, { toggleFollowed(id) } Text("Compose") } › Required
parameters › Optional parameters › First one: Modifier › Trailing content lambda fun NiaTopicTag( followed: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, text: @Composable () -> Unit, ) ) { @Composable -
Ordering parameters NiaTopicTag(followed = true, onClick = { toggleFollowed(id) }
Text("Compose") } › Required parameters › Optional parameters › First one: Modifier › Trailing content lambda fun NiaTopicTag( followed: Boolean, onClick: () -> Unit, text: @Composable () -> Unit, ) modifier: Modifier = Modifier, enabled: Boolean = true, ) { @Composable -
Ordering parameters NiaTopicTag(true, Text("Compose") } › Required parameters › Optional
parameters › First one: Modifier › Trailing content lambda fun NiaTopicTag( followed: Boolean, onClick: () -> Unit, text: @Composable () -> Unit, ) modifier: Modifier = Modifier, enabled: Boolean = true, ) { { toggleFollowed(id) } @Composable -
Ordering parameters NiaTopicTag(true, , Modifier.padding(8.dp) Text("Compose") } fun NiaTopicTag( followed:
Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, text: @Composable () -> Unit, ) › Required parameters › Optional parameters › First one: Modifier › Trailing content lambda { toggleFollowed(id) } ) { @Composable -
Ordering parameters NiaTopicTag(true, { toggleFollowed(id) }, Modifier.padding(8.dp)) { Text("Compose") }
fun NiaTopicTag( followed: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, text: @Composable () -> Unit, ) › Required parameters › Optional parameters › First one: Modifier › Trailing content lambda @Composable -
Ordering parameters NiaTopicTag(true, { toggleFollowed(id) }, Modifier.padding(8.dp)) { Text("Compose") }
fun NiaTopicTag( followed: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, content: @Composable () -> Unit, ) › Required parameters › Optional parameters › First one: Modifier › Trailing content lambda @Composable -
@Composable fun Scroller( offset: MutableState< >, ) { offset.value =
42f } State Float -
@Composable fun Scroller( offset: State<Float>, onOffsetChange: (Float) -> Unit, )
@Composable fun ContextMenu(offset: Float, onOffsetChange: (Float) -> Unit) { Row { MenuItems() Scroller(offset, onOffsetChange) } } State -
@Composable fun Scroller( offset: State<Float>, onOffsetChange: (Float) -> Unit, )
@Composable fun ContextMenu(offset: Float, onOffsetChange: (Float) -> Unit) { val offsetState = remember { mutableStateOf(offset) } Row { MenuItems() Scroller(offsetState, onOffsetChange) } } State -
@Composable fun Scroller( offset: () -> Float, onOffsetChange: (Float) ->
Unit, ) // Constant Scroller(offset = { 0f }, ...) // Plain value Scroller(offset = { offset }, ...) // State Scroller(offset = { offsetState.value }, ...) // Value from an object Scroller(offset = { someObject.offset }, ...) State -
@Composable fun Scroller( offset: () -> Float, onOffsetChange: (Float) ->
Unit, ) // Constant Scroller(offset = { 0f }, ...) // Plain value Scroller(offset = { offset }, ...) // State Scroller(offset = { offsetState.value }, ...) // Value from an object Scroller(offset = { someObject.offset }, ...) State jb.gg/debugging-recomposition -
State holders @Composable fun VerticalScroller( , , onScrollPositionChange: (Int) ->
Unit, onScrollRangeChange: (Int) -> Unit, ) scrollPosition: Int scrollRange: Int -
State holders @Composable fun VerticalScroller( ) @Stable interface VerticalScrollerState {
var var } scrollPosition: Int scrollRange: Int -
State holders @Composable fun VerticalScroller( verticalScrollerState: VerticalScrollerState ) @Stable interface
VerticalScrollerState { } scrollPosition: Int scrollRange: Int var var -
State holders @Composable fun VerticalScroller( verticalScrollerState: VerticalScrollerState ) @Stable interface
VerticalScrollerState { } scrollPosition: Int scrollRange: Int var var -
State holders @Stable interface { } jb.gg/compose-stability @Composable fun VerticalScroller(
verticalScrollerState: VerticalScrollerState ) VerticalScrollerState scrollPosition: Int scrollRange: Int var var -
State holders class Impl( scrollPosition: Int = 0, scrollRange: Int
= 0, ) : VerticalScrollerState { override by mutableStateOf(scrollPosition) override by mutableStateOf(scrollRange) } @Composable fun VerticalScroller( verticalScrollerState: VerticalScrollerState ) VerticalScrollerState scrollPosition: Int scrollRange: Int var var -
State holders @Composable fun VerticalScroller( verticalScrollerState: VerticalScrollerState ) fun VerticalScrollerState():
VerticalScrollerState = VerticalScrollerStateImpl() private class Impl( scrollPosition: Int = 0, scrollRange: Int = 0, ) : VerticalScrollerState { override var scrollPosition: Int by mutableStateOf(scrollPosition) override var scrollRange: Int by mutableStateOf(scrollRange) } VerticalScrollerState -
State holders @Composable fun VerticalScroller( verticalScrollerState: VerticalScrollerState = remember {
VerticalScrollerState() } ) fun VerticalScrollerState(): VerticalScrollerState = VerticalScrollerStateImpl() private class Impl( scrollPosition: Int = 0, scrollRange: Int = 0, ) : VerticalScrollerState { override var scrollPosition: Int by mutableStateOf(scrollPosition) override var scrollRange: Int by mutableStateOf(scrollRange) } VerticalScrollerState -
State holders @Composable fun VerticalScroller( verticalScrollerState: VerticalScrollerState = remember {
VerticalScrollerState() } ) fun VerticalScrollerState(): VerticalScrollerState = VerticalScrollerStateImpl() @Stable interface VerticalScrollerState { var scrollPosition: Int var scrollRange: Int } private class Impl( scrollPosition: Int = 0, scrollRange: Int = 0, ) : VerticalScrollerState { override var scrollPosition: Int by mutableStateOf(scrollPosition) override var scrollRange: Int by mutableStateOf(scrollRange) } VerticalScrollerState -
State holders @Stable class VerticalScrollerState { var scrollPosition: Int by
mutableStateOf(0) var scrollRange: Int by mutableStateOf(0) } -
State holders @Stable class VerticalScrollerState { var scrollPosition: Int by
mutableStateOf(0) var scrollRange: Int by mutableStateOf(0) } -
Compose Multiplatform jb.gg/compose Guidelines jb.gg/compose-api-guidelines jb.gg/compose-component-api- guidelines
In order of appearance jb.gg/composition-locals jb.gg/compose-modifiers jb.gg/movable-content-of jb.gg/debugging-recomposition jb.gg/compose-stability jb.gg/io24-compose-apis jb.gg/compose-rules Composing an API the way zsmb.co/talks Márton Braun @[email protected]