Skip to content

Instantly share code, notes, and snippets.

@Sottti
Created October 23, 2025 14:07
Show Gist options
  • Select an option

  • Save Sottti/a8517b5140aeff26cbfcd96e1530ca85 to your computer and use it in GitHub Desktop.

Select an option

Save Sottti/a8517b5140aeff26cbfcd96e1530ca85 to your computer and use it in GitHub Desktop.
import android.content.ComponentCallbacks
import android.content.Context
import android.content.res.Configuration
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.distinctUntilChanged
public fun <T> Context.observeConfigurationChanges(
getValue: () -> T,
): Flow<T> = callbackFlow {
trySend(getValue())
val callbacks = object : ComponentCallbacks {
override fun onConfigurationChanged(newConfig: Configuration) {
trySend(getValue())
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onLowMemory() = Unit
}
registerComponentCallbacks(callbacks)
awaitClose { unregisterComponentCallbacks(callbacks) }
}
.distinctUntilChanged()
.conflate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment