Skip to content

Instantly share code, notes, and snippets.

@chitrang200889
Last active January 23, 2024 04:09
Show Gist options
  • Save chitrang200889/3ff7702842b199958cb118657df0885b to your computer and use it in GitHub Desktop.
Save chitrang200889/3ff7702842b199958cb118657df0885b to your computer and use it in GitHub Desktop.
Recompose Entire Screen
data class UiState(
val sellerCount: Int,
val buyerCount: Int
)
class MainActivity : ComponentActivity() {
private val _uiState = MutableStateFlow<UiState>(
UiState(
sellerCount = 0,
buyerCount = 0
)
)
val uiState: StateFlow<UiState> = _uiState
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RecomposeTestTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val screenUiState = uiState.collectAsState().value
Column {
SellerUiComponent(
sellerCount = screenUiState.sellerCount,
onClickSellerIncrement = {
_uiState.update {
it.copy(
sellerCount = it.sellerCount + 1
)
}
}
)
BuyerUiComponent(
buyerCount = screenUiState.buyerCount,
onClickBuyerIncrement = {
_uiState.update {
it.copy(
buyerCount = it.buyerCount + 1
)
}
}
)
}
}
}
}
}
}
/**
* Solution 1: Large UiState that recompose entire screen.
*/
@Composable
fun SellerUiComponent(sellerCount: Int, onClickSellerIncrement: () -> Unit) {
Button(
onClick = onClickSellerIncrement,
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(16.dp)
) {
Text(text = "Increase Seller")
}
Text(
text = "Seller Count $sellerCount",
modifier = Modifier.padding(16.dp)
)
}
@Composable
fun BuyerUiComponent(buyerCount: Int, onClickBuyerIncrement: () -> Unit) {
Button(
onClick = onClickBuyerIncrement,
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(16.dp)
) {
Text(text = "Increase Buyer")
}
Text(
text = "Buyer Count $buyerCount",
modifier = Modifier.padding(16.dp)
)
}
@chitrang200889
Copy link
Author

Observe that while clicking on a button of individual UiComponent entire screen is getting recomposed.

RecomposeEntireScreen.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment