Skip to content

Instantly share code, notes, and snippets.

@chitrang200889
Created January 22, 2024 06:22
Show Gist options
  • Save chitrang200889/28600e4ef8a023a66bec121acbbebe3a to your computer and use it in GitHub Desktop.
Save chitrang200889/28600e4ef8a023a66bec121acbbebe3a to your computer and use it in GitHub Desktop.
Recompose UiComponent Only
data class SellerData(val count: Int)
data class BuyerData(val count: Int)
@Stable
class UiState {
val sellerData = mutableStateOf<SellerData>(SellerData(0))
val buyerData = mutableStateOf<BuyerData>(BuyerData(0))
}
class MainActivity : ComponentActivity() {
private val _uiState = MutableStateFlow<UiState>(UiState())
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(screenUiState.sellerData)
BuyerUiComponent(screenUiState.buyerData)
}
}
}
}
}
}
/**
* Solution 2: Smaller MutableState that recompose only UI Component.
*/
@Composable
fun SellerUiComponent(sellerData: MutableState<SellerData>) {
Button(
onClick = { sellerData.value = sellerData.value.copy(sellerData.value.count + 1) },
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(16.dp)
) {
Text(text = "Increase Seller")
}
Text(
text = "Seller Count ${sellerData.value.count}",
modifier = Modifier.padding(16.dp)
)
}
@Composable
fun BuyerUiComponent(buyerData: MutableState<BuyerData>) {
Button(
onClick = { buyerData.value = buyerData.value.copy(buyerData.value.count + 1) },
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(16.dp)
) {
Text(text = "Increase Buyer")
}
Text(
text = "Buyer Count ${buyerData.value.count}",
modifier = Modifier.padding(16.dp)
)
}
@chitrang200889
Copy link
Author

chitrang200889 commented Jan 22, 2024

Observe that while clicking on a button of individual UiComponent, only that UiComponent gets updated and not the entire screen.

RecomposeUiComponentOnly.mov

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