I'm trying to rewrite my old code in Jetpack Compose, but I have trouble with ContentResolver.addStatusChangeListener which is not firing sync events. I'm using the same business logic (viewmodel, repository) for both - classic UI and compose, but in compose it's not working.
Here is the classic UI code:
private var syncStatusHandle: Any? = null
override fun onResume() {
super.onResume()
syncStatusHandle = ContentResolver.addStatusChangeListener(
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE or ContentResolver.SYNC_OBSERVER_TYPE_PENDING
)
{
Timber.d("sync event fired")
}
}
override fun onPause() {
super.onPause()
if (syncStatusHandle != null) {
ContentResolver.removeStatusChangeListener(syncStatusHandle)
}
}
And here is how it looks like in Compose (It's pretty much the same approach as mentioned in the docs: Interoperability APIs):
@Composable
fun SyncStatusManager(
onSyncEvent: (count: Int) -> Unit
) {
val context = LocalContext.current
val currentOnSyncEvent by rememberUpdatedState(onSyncEvent)
DisposableEffect(context) {
val syncStatusHandle = ContentResolver.addStatusChangeListener(
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE or ContentResolver.SYNC_OBSERVER_TYPE_PENDING
)
{
currentOnSyncEvent(it)
}
onDispose {
ContentResolver.removeStatusChangeListener(syncStatusHandle)
}
}
}
and it's used in different composable like this:
SyncStatusManager {
Timber.d("sync event should be fired, but it's not")
}
I tried to use LaunchEffect, or not Effects at all, but no success. When I trigger sync, the callback should fire immediately but it doesn't. am I missing something ? I'm new to Jetpack Compose. Thank you (Necessary permissions are granted in both cases)