Share
Android UIs at Scale: UI Architecture in the Compose world
These are the slides from the 360AnDev 2021 version of the talk "Android UIs at Scale: UI Architecture in the Compose world".
Android UIs are experiencing a paradigm shift with the advent of Jetpack Compose, and it's necessary for us to prepare for it.
As we navigate these weird times for UI development in Android, we need to have a strategy in place to adopt Compose, but how can we embrace Compose, while maintaining our current UI in a good state? What does an architecture that plays nice with Views and Composables look like?
In this session I will describe the mechanisms that we use at Twitter to create UI components. I will explain how we manage their reusability and encapsulation, how our stateful UI components look like, how they work with Android Views and Composables and how the migration path between them.
Nacho L.
Transcript
160 slides
-
UI Architecture in the Compose world Android UIs at Scale
360|AnDev 2021 -
A long time ago in a galaxy far, far away
… Well, actually… it was in 2017 -
19 interface ViewModel interface Binder { fun bind(viewDelegate: ViewDelegate, viewModel:
ViewModel): Disposable } interface ViewDelegate<out V: View> { protected val rootView: V } -
20 interface ViewModel interface Binder { fun bind(viewDelegate: ViewDelegate, viewModel:
ViewModel): Disposable } interface ViewDelegate<out V: View> { protected val rootView: V } But it still was too unopinionated -
ViewModel interface Binder { fun bind(viewDelegate: ViewDelegate, viewModel: ViewModel): Disposable
} interface ViewDelegate<out V: View> { protected val rootView: V } interface -
ViewModel interface Binder { fun bind(viewDelegate: ViewDelegate, viewModel: ViewModel): Disposable
} interface ViewDelegate<out V: View> { protected val rootView: V } interface -
ViewModel class MyViewModel : { internal fun textChanged(): Observable<String> =
... internal fun respondToButtonClick() { ... } fun updateText(text: String) { ... } } -
ViewModel class MyViewModel : { internal fun textChanged(): Observable<String> =
... } internal fun onButtonClicked(): Observable<View> = button.clicks() } -
) : ViewDelegate<ConstraintLayout> { private val button = rootView.findViewById<Button>(R.id.button1) internal
fun setText(text: String) { . -
) : ViewDelegate<ConstraintLayout> { private val button = rootView.findViewById<Button>(R.id.button1) internal
fun setText(text: String) { . -
interface ViewModel<VS: ViewState, I: UserIntent> { fun stateObservable(): Observable<VS> fun
processUserIntent(intent: I) } class WeaverViewBinder : Binder { fun bind(viewDelegate: ViewDelegate, viewModel: ViewModel): Disposable { val disposables = CompositeDisposable() disposables += viewModel.stateObservable() .subscribe { state > -
interface ViewModel<VS: ViewState, I: UserIntent> { fun stateObservable(): Observable<VS> fun
processUserIntent(intent: I) } interface ViewDelegate<out V: View, VS: ViewState, I: UserIntent> { protected val rootView: V fun render(state: VS) fun userIntentObservable(): Observable<I> = Observable.never() } class WeaverViewBinder : Binder { fun bind(viewDelegate: ViewDelegate, viewModel: ViewModel): Disposable { val disposables = CompositeDisposable() disposables += viewModel.stateObservable() .subscribe { state > -
interface ViewDelegate<out V: View, VS: ViewState, I: UserIntent> { protected
val rootView: V fun render(state: VS) fun userIntentObservable(): Observable<I> = Observable.never() } class WeaverViewBinder : Binder { fun bind(viewDelegate: ViewDelegate, viewModel: ViewModel): Disposable { val disposables = CompositeDisposable() disposables += viewModel.stateObservable() .subscribe { state -> viewDelegate.render(state) } disposables += viewDelegate.userIntentObservable() .subscribe { intent -> viewModel.processUserIntent(intent) } return disposables } } -
interface ViewDelegate<out V: View, VS: ViewState, I: UserIntent> { protected
val rootView: V fun render(state: VS) fun userIntentObservable(): Observable<I> = Observable.never() } class WeaverViewBinder : Binder { fun bind(viewDelegate: ViewDelegate, viewModel: ViewModel): Disposable { val disposables = CompositeDisposable() disposables += viewModel.stateObservable() .subscribe { state > -
interface ViewDelegate<out V: View, VS: ViewState, I: UserIntent> { protected
val rootView: V fun render(state: VS) fun userIntentObservable(): Observable<I> = Observable.never() } class WeaverViewBinder : Binder { fun bind(viewDelegate: ViewDelegate, viewModel: ViewModel): Disposable { val disposables = CompositeDisposable() disposables += viewModel.stateObservable() .subscribe { state > -
What we use: Weaver [CHIRPBIRDI CO N] ’s MVI +
Data binding UI architecture framework -
1. Data binding What is Weaver? <FrameLayout android:id="@+id/my_layout" ... >
<tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> -
1. Data binding What is Weaver? <FrameLayout android:id="@+id/my_layout" ... >
<tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> -
1. Data binding What is Weaver? <FrameLayout android:id="@+id/my_layout" ... >
<tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> -
1. Data binding What is Weaver? <FrameLayout android:id="@+id/my_layout" ... >
<tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> -
1. Data binding What is Weaver? <FrameLayout android:id="@+id/my_layout" ... >
<tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> 2. MVI -
2. MVI What is Weaver? setState { ... } onSuccess
{ value -> ... } onFailure { throwable -> ... } onSuccessOrFailure { result -> ... } onComplete { ... } } yieldEffect( . -
2. MVI What is Weaver? setState { -> ... }
yieldEffect( . -
What is Weaver? 4. Standalone components class MyFeatureActivity : InjectedFragmentActivity()
<FrameLayout android:id="@+id/my_layout" ... > <tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> -
What is Weaver? 4. Standalone components class MyFeatureActivity : InjectedFragmentActivity()
<FrameLayout android:id="@+id/my_layout" ... > <tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> -
What is Weaver? 4. Standalone components class MyFeatureActivity : InjectedFragmentActivity()
<FrameLayout android:id="@+id/my_layout" ... > <tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> -
What is Weaver? 4. Standalone components class MyFeatureActivity : InjectedFragmentActivity()
<FrameLayout android:id="@+id/my_layout" ... > <tag android:id="@id/weaverComponent" android:value="MyComponent" /> </ FrameLayout> 5. Easy threading -
What is Weaver? 5. 6. Painless subscriptions 7. Testing framework
8. IDE support Easy threading -
What is Weaver? 5. 6. 7. 8. Painless subscriptions Easy
threading Testing framework IDE support -
& Mental model is the same Instead of having 3
building blocks, we only need 1 in Compose: the ViewModel. -
& Mental model is the same Binders, Views unnecessary To
provide everything necessary we will need some configuration via CompositionLocal Cohesive entrypoints -
& val viewModel = weaverViewModel<MyViewModel>() val value by viewModel.watchAsState(MyViewState ::
value) val state by viewModel.watchAsState() -
& val viewModel = weaverViewModel<MyViewModel>() val values by viewModel.watchAsState(MyViewState ::
value1, MyViewState :: value2, …) val (value1, value2, ... ) = values val value by viewModel.watchAsState(MyViewState : -
& val viewModel = weaverViewModel<MyViewModel>() viewModel.subscribeEffects { ... } val
values by viewModel.watchAsState(MyViewState : -
& @Composable fun FollowButton() { val viewModel = weaverViewModel<FollowViewModel>() val
isFollowing by viewModel.watchAsState(FollowViewState :: following) FollowButton(isFollowing) { viewModel.toggleFollow() } } -
& @Composable fun FollowButton() { val viewModel = weaverViewModel<FollowViewModel>() val
isFollowing by viewModel.watchAsState(FollowViewState :: following) FollowButton(isFollowing) { viewModel.toggleFollow() } } @Composable fun FollowButton( isFollowing: Boolean, onClick: () -> Unit ) { ... } -
& @Composable fun FollowButton() { val viewModel = weaverViewModel<FollowViewModel>() val
isFollowing by viewModel.watchAsState(FollowViewState :: following) FollowButton(isFollowing) { viewModel.toggleFollow() } } @Composable fun FollowButton( isFollowing: Boolean, onClick: () -> Unit ) { ... } -
& @Composable fun FollowButton() { val viewModel = weaverViewModel<FollowViewModel>() val
isFollowing by viewModel.watchAsState(FollowViewState :: following) FollowButton(isFollowing) { viewModel.toggleFollow() } } @Composable fun FollowButton( isFollowing: Boolean, onClick: () -> Unit ) { ... } -
& @Composable fun FollowButton() { val viewModel = weaverViewModel<FollowViewModel>() val
isFollowing by viewModel.watchAsState(FollowViewState :: following) FollowButton(isFollowing) { viewModel.toggleFollow() } } @Composable fun FollowButton( isFollowing: Boolean, onClick: () -> Unit ) { ... } -
& @Composable fun FollowButton() { val viewModel = weaverViewModel<FollowViewModel>() val
isFollowing by viewModel.watchAsState(FollowViewState :: following) FollowButton(isFollowing) { viewModel.toggleFollow() } } @Composable fun FollowButton( isFollowing: Boolean, onClick: () -> Unit ) { ... } -
& strategy 1. Proof of concept 2. Prepare the build
to make sure that Compose or the new IR backend properly built on CI. -
& strategy 2. Adding to the build 3. Design system
Robust theming and ways to customize for special cases. -
& strategy 3. Design system 4. Early Access Program Partner
up with select feature teams of different needs and allow them to early adopt Compose. Provide hands on support to them. They will find all the possible ways your infra is broken and how your APIs suck. Fix, document. -
& strategy 4. Early Access Program 5. Hype train Education
is king on such a big change. Make sure to communicate internally about Compose, with comprehensive documentation and education sessions / talks / codelabs. -
& strategy 5. Hype train 6. Broad adoption Open the
floodgates for more feature teams to use it. -
& strategy 6. Broad adoption 7. Long term support Team
ownership on upgrading the Compose dependencies. Integration and instrumentation testing are key to make sure the core infra doesn’t break between updates. [CHIRPBIRDI CO N] feature devs -
@Composable fun TopicsHeader() { val viewModel = weaverViewModel<TopicHeaderViewModel>() val state
by viewModel.watchAsState() Title(state.title) Subtitle(state.subtitle) Row { Facepile(state.users) FollowButton(state.following) { viewModel.toggleFollow() } } Description(state.description) Timeline(state.timeline) } -
@Composable fun TopicsHeader() { val viewModel = weaverViewModel<TopicHeaderViewModel>() val state
by viewModel.watchAsState() Title(state.title) Subtitle(state.subtitle) Row { Facepile(state.users) FollowButton(state.following) { viewModel.toggleFollow() } } Description(state.description) Timeline(state.timeline) } -
@Composable fun TopicsHeader() { val viewModel = weaverViewModel<TopicHeaderViewModel>() val state
by viewModel.watchAsState() Title(state.title) Subtitle(state.subtitle) Row { Facepile(state.users) FollowButton(state.following) { viewModel.toggleFollow() } } Description(state.description) Timeline(state.timeline) } Business logic is reused -
@Composable fun TopicsHeader() { val viewModel = weaverViewModel<TopicHeaderViewModel>() val state
by viewModel.watchAsState() Title(state.title) Subtitle(state.subtitle) Row { Facepile(state.users) FollowButton(state.following) { viewModel.toggleFollow() } } Description(state.description) Timeline(state.timeline) } -
@Composable fun TopicsHeader() { val viewModel = weaverViewModel<TopicHeaderViewModel>() val state
by viewModel.watchAsState() Title(state.title) Subtitle(state.subtitle) Row { Facepile(state.users) FollowButton(state.following) { viewModel.toggleFollow() } } Description(state.description) Timeline(state.timeline) } -
@Composable fun Facepile(twitterUsers: List<TwitterUser>, membersClicked: () -> Unit) { val
borderColor = HorizonTheme.colors.primary.toArgb() AndroidView( :: FacePileView) { facePileView: FacePileView -> facePileView.avatarBorderColor = borderColor facePileView.initFaces(twitterUsers.take(3).reversed()) facePileView.setOnClickListener { membersClicked() } } } -
@Composable fun Facepile(twitterUsers: List<TwitterUser>, membersClicked: () -> Unit) { val
borderColor = HorizonTheme.colors.primary.toArgb() AndroidView( :: FacePileView) { facePileView: FacePileView -> facePileView.avatarBorderColor = borderColor facePileView.initFaces(twitterUsers.take(3).reversed()) facePileView.setOnClickListener { membersClicked() } } } -
android:id="@+id/send_dm" style="@style/TwitterButtonMediumBorderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/send_dm" /> android:id="@+id/follow" style="@style/TwitterButtonMediumBorderless" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="@string/follow" /> <com.twitter.ui.components.button.TwitterButton <com.twitter.ui.components.button.TwitterButton -
android:id="@+id/send_dm" style="@style/TwitterButtonMediumBorderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/send_dm" /> android:id="@+id/follow" style="@style/TwitterButtonMediumBorderless" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="@string/follow" /> <com.twitter.ui.components.button.TwitterButton <com.twitter.ui.components.button.TwitterButton -
android:id="@+id/send_dm" style="@style/TwitterButtonMediumBorderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/send_dm" /> android:id="@+id/follow" style="@style/TwitterButtonMediumBorderless" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="@string/follow" /> <com.twitter.ui.components.button. <com.twitter.ui.components.button.HorizonComposeButton HorizonComposeButton -
class @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr:
Int = 0 ) : AbstractComposeView(context, attrs, defStyleAttr), HorizonButton { HorizonComposeButton } -
class @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr:
Int = 0 ) : AbstractComposeView(context, attrs, defStyleAttr), HorizonButton { HorizonComposeButton } -
class @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr:
Int = 0 ) : AbstractComposeView(context, attrs, defStyleAttr), HorizonButton { HorizonComposeButton } private var onClick by mutableStateOf({}) private var buttonText: CharSequence? by mutableStateOf("") override fun getText(): CharSequence? = buttonText override fun setText(value: CharSequence?) { buttonText = value } // ... -
class @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr:
Int = 0 ) : AbstractComposeView(context, attrs, defStyleAttr), HorizonButton { HorizonComposeButton } @Composable override fun Content() { HorizonTheme { HorizonButton(_text, onClick, ... ) } } // ... -
private val styleButtonAppearanceMap by lazy { fun bold(size: ButtonSize) =
ButtonStyle(size, ButtonType.Outlined, ButtonColors.Legacy.Primary) fun heavy(size: ButtonSize) = ButtonStyle(size, ButtonType.Filled, ButtonColors.Legacy.Primary) fun regular(size: ButtonSize) = ButtonStyle(size, ButtonType.Outlined, ButtonColors.Legacy.Regular) // ... mapOf( R.style.TwitterButtonLargeBold to bold(ButtonSize.Legacy.Large()), R.style.TwitterButtonSmallBold to bold(ButtonSize.Legacy.Small()), // ... ) } internal fun styleToButtonAppearance(@StyleRes styleResId: Int): ButtonStyle = styleButtonAppearanceMap[styleResId] ?: error("There is no mapping for this legacy style.") -
private val styleButtonAppearanceMap by lazy { fun bold(size: ButtonSize) =
ButtonStyle(size, ButtonType.Outlined, ButtonColors.Legacy.Primary) fun heavy(size: ButtonSize) = ButtonStyle(size, ButtonType.Filled, ButtonColors.Legacy.Primary) fun regular(size: ButtonSize) = ButtonStyle(size, ButtonType.Outlined, ButtonColors.Legacy.Regular) // ... mapOf( R.style.TwitterButtonLargeBold to bold(ButtonSize.Legacy.Large()), R.style.TwitterButtonSmallBold to bold(ButtonSize.Legacy.Small()), // ... ) } internal fun styleToButtonAppearance(@StyleRes styleResId: Int): ButtonStyle = styleButtonAppearanceMap[styleResId] ?: error("There is no mapping for this legacy style.") -
<style name="SharedTheme" parent="ThemeBase"> <item name="viewInflaterClass">com.twitter.ui.CustomViewInflater </ item> ... </ style>
class CustomViewInflater : AppCompatViewInflater() { override fun createView(context: Context, name: String, attrs: AttributeSet): View { if ( name == TwitterButton :: class.java.canonicalName && HorizonComposeButtonUtils.isComposeButtonEnabled() ) { HorizonComposeButton(context, name, attrs) } else { super.createView(context, name, attrs) } } } -
<style name="SharedTheme" parent="ThemeBase"> <item name="viewInflaterClass">com.twitter.ui.CustomViewInflater </ item> ... </ style>
class CustomViewInflater : AppCompatViewInflater() { override fun createView(context: Context, name: String, attrs: AttributeSet): View { if ( name == TwitterButton :: class.java.canonicalName && HorizonComposeButtonUtils.isComposeButtonEnabled() ) { HorizonComposeButton(context, name, attrs) } else { super.createView(context, name, attrs) } } } -
class CustomViewInflater : AppCompatViewInflater() { override fun createView(context: Context, name:
String, attrs: AttributeSet): View { if ( name == TwitterButton :: class.java.canonicalName && HorizonComposeButtonUtils.isComposeButtonEnabled() ) { HorizonComposeButton(context, name, attrs) } else { super.createView(context, name, attrs) } } } <style name="SharedTheme" parent="ThemeBase"> <item name="viewInflaterClass">com.twitter.ui.CustomViewInflater </ item> ... </ style> -
class CustomViewInflater : AppCompatViewInflater() { override fun createView(context: Context, name:
String, attrs: AttributeSet): View { if ( name == TwitterButton :: class.java.canonicalName && HorizonComposeButtonUtils.isComposeButtonEnabled() ) { HorizonComposeButton(context, name, attrs) } else { super.createView(context, name, attrs) } } } But what if we want to be selective? -
class CustomViewInflater : AppCompatViewInflater() { override fun createView(context: Context, name:
String, attrs: AttributeSet): View { if ( name == TwitterButton :: class.java.canonicalName && HorizonComposeButtonUtils.isComposeButtonEnabled() ) { HorizonComposeButton(context, name, attrs) } else { super.createView(context, name, attrs) } } } But what if we want to be selective? -
class CustomViewInflater : AppCompatViewInflater() { override fun createView(context: Context, name:
String, attrs: AttributeSet): View { if ( name == && HorizonComposeButtonUtils.isComposeButtonEnabled() ) { HorizonComposeButton(context, name, attrs) } else { super.createView(context, name, attrs) } } } But what if we want to be selective? MigrationTwitterButton :: class.java.canonicalName -
if ( name == && HorizonComposeButtonUtils.isComposeButtonEnabled() ) { HorizonComposeButton(context, name,
attrs) } else { super.createView(context, name, attrs) } } } But what if we want to be selective? MigrationTwitterButton :: class.java.canonicalName class MigrationTwitterButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : TwitterButton(context, attrs, defStyleAttr) -
But what if we want to be selective? <com.twitter.ui.components.button.TwitterButton <com.twitter.ui.components.button.MigrationTwitterButton
class MigrationTwitterButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : TwitterButton(context, attrs, defStyleAttr) -
Use a different subclass of the UI element for what
you want to migrate -
val button = context.findViewById< button.setText(R.string.my_new_fancy_text) HorizonButton>() class HorizonComposeButton @JvmOverloads constructor(
... ) : AbstractComposeView(context, attrs, defStyleAttr), HorizonButton class TwitterButton @JvmOverloads constructor( ... ) : AppCompatButton(context, attrs, defStyleAttr), HorizonButton -
val button = context.findViewById< button.setText(R.string.my_new_fancy_text) HorizonButton>() class HorizonComposeButton @JvmOverloads constructor(
... ) : AbstractComposeView(context, attrs, defStyleAttr), HorizonButton class TwitterButton @JvmOverloads constructor( ... ) : AppCompatButton(context, attrs, defStyleAttr), HorizonButton -
public interface { // Omit nullity annotation to maintain compatibility
with TextView's getText() // that returns platform type CharSequence getText(); void setText(@Nullable CharSequence charSequence); void setIcon(@DrawableRes int iconDrawable); boolean isEnabled(); void setEnabled(boolean enabled); int getVisibility(); void setVisibility(int visibility); void setOnClickListener(@Nullable View.OnClickListener listener); void setTag(@Nullable Object action); void setContentDescription(@Nullable CharSequence contentDescription); boolean callOnClick(); HorizonButton } -
class HorizonComposeButton( ... ) : AbstractComposeView( ... ), HorizonButton {
var text = mutableStateOf("") init { context.withStyledAttributes(attrs, R.styleable.HorizonComposeButton, defAttrs) { text = getString(R.styleable.HorizonComposeButton_android_text) ?: "" } } Text(text) } } @Composable override fun Content() { -
Text(text) } } class HorizonComposeButton( ... ) : AbstractComposeView( ...
), HorizonButton { var text = mutableStateOf("") init { context.withStyledAttributes(attrs, R.styleable.HorizonComposeButton, defAttrs) { text = getString(R.styleable.HorizonComposeButton_android_text) ?: "" } } @Composable override fun Content() { -
Text(text) } } class HorizonComposeButton( ... ) : AbstractComposeView( ...
), HorizonButton { @Composable override fun Content() { val viewModel = weaverViewModel<HorizonButtonViewModel>(id) val text by viewModel.watchAsState(HorizonButtonState :: text) -
} } class HorizonComposeButton( ... ) : AbstractComposeView( ... ),
HorizonButton { var text = mutableStateOf("") init { context.withStyledAttributes(attrs, R.styleable.HorizonComposeButton, defAttrs) { text = getString(R.styleable.HorizonComposeButton_android_text) ?: "" } } @Composable override fun Content() { val internalText = rememberSaveable { text } Text(internalText) -
} } class HorizonComposeButton( ... ) : AbstractComposeView( ... ),
HorizonButton { var text = mutableStateOf("") init { context.withStyledAttributes(attrs, R.styleable.HorizonComposeButton, defAttrs) { text = getString(R.styleable.HorizonComposeButton_android_text) ?: "" } } @Composable override fun Content() { val internalText = rememberSaveable { text } Text(internalText) -
} } class HorizonComposeButton( ... ) : AbstractComposeView( ... ),
HorizonButton { var text = mutableStateOf("") init { context.withStyledAttributes(attrs, R.styleable.HorizonComposeButton, defAttrs) { text = getString(R.styleable.HorizonComposeButton_android_text) ?: "" } } @Composable override fun Content() { val internalText = rememberSaveable { text } Text(internalText) SideEffect { if (textInternal != text) { text = textInternal } }