Last active
January 23, 2024 04:09
-
-
Save chitrang200889/3ff7702842b199958cb118657df0885b to your computer and use it in GitHub Desktop.
Recompose Entire Screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Observe that while clicking on a button of individual UiComponent entire screen is getting recomposed.
RecomposeEntireScreen.mov