Created
January 22, 2024 06:22
-
-
Save chitrang200889/28600e4ef8a023a66bec121acbbebe3a to your computer and use it in GitHub Desktop.
Recompose UiComponent Only
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 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) | |
) | |
} |
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, only that UiComponent gets updated and not the entire screen.
RecomposeUiComponentOnly.mov