Skip to content

Instantly share code, notes, and snippets.

@lub0s
Created April 15, 2022 11:42
Show Gist options
  • Save lub0s/8fecacde625a4c8c47e38c13d6d666c0 to your computer and use it in GitHub Desktop.
Save lub0s/8fecacde625a4c8c47e38c13d6d666c0 to your computer and use it in GitHub Desktop.
Difference in recomposition when using offset modfier in Jetpack Compose
@HiltViewModel
class UpdatingViewModel @Inject constructor() : ViewModel() {
val offset = mutableStateOf(Offset(0f, 0f))
init {
viewModelScope.launch {
while(isActive) {
delay(50)
offset.value = offset.value.copy(x = offset.value.x + 1)
}
}
}
}
@Composable
fun OffsetsSample(
vm: UpdatingViewModel = hiltViewModel()
) {
Column(
modifier = Modifier.systemBarsPadding(),
) {
RecomposingOffset(offset = vm.offset)
NonRecomposingOffset(offset = vm.offset)
}
}
@Composable
private fun RecomposingOffset(
modifier: Modifier = Modifier,
offset: State<Offset>
) {
LogRecompose(composableTag = "Recomposing")
Text(
text = "Recomposing",
modifier = modifier.fillMaxWidth().offset(
x = with(LocalDensity.current) { offset.value.x.toDp() },
y = with(LocalDensity.current) { offset.value.y.toDp() },
)
)
}
@Composable
private fun NonRecomposingOffset(
modifier: Modifier = Modifier,
offset: State<Offset>
) {
LogRecompose(composableTag = "NonRecomposing")
Text(
text = "NonRecomposing",
modifier = modifier.fillMaxWidth().offset {
IntOffset(
offset.value.x.roundToInt(),
offset.value.y.roundToInt()
)
}
)
}
class Ref(var value: Int)
@Composable
inline fun LogRecompose(composableTag: String) {
val ref = remember { Ref(0) }
SideEffect { ref.value++ }
Log.d(composableTag, "recomposed ${ref.value} times")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment