From 41960f87551f1a420c50032fd071a22868f7709b Mon Sep 17 00:00:00 2001 From: Shreyas Patil Date: Sun, 3 Mar 2024 16:50:42 +0530 Subject: [PATCH] [#64] Add support for getting state as events --- .../watchmen/PermissionWatchmen.kt | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/permission-flow/src/main/java/dev/shreyaspatil/permissionFlow/watchmen/PermissionWatchmen.kt b/permission-flow/src/main/java/dev/shreyaspatil/permissionFlow/watchmen/PermissionWatchmen.kt index 8785c27..8950ba7 100644 --- a/permission-flow/src/main/java/dev/shreyaspatil/permissionFlow/watchmen/PermissionWatchmen.kt +++ b/permission-flow/src/main/java/dev/shreyaspatil/permissionFlow/watchmen/PermissionWatchmen.kt @@ -26,10 +26,13 @@ import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelChildren +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch @@ -77,6 +80,24 @@ internal class PermissionWatchmen( return combineStates(*permissionStates) { MultiplePermissionState(it.toList()) } } + fun watchStateEvents(permission: String): Flow { + // Wakeup watchmen if sleeping + wakeUp() + return getPermissionEvent(permission) + } + + fun watchMultipleStateEvents(permissions: Array): Flow { + // Wakeup watchmen if sleeping + wakeUp() + + val permissionStates = permissions + .distinct() + .map { permission -> getPermissionEvent(permission) } + .toTypedArray() + + return combine(*permissionStates) { MultiplePermissionState(it.toList()) } + } + fun notifyPermissionsChanged(permissions: Array) { watchmenScope.launch { permissions.forEach { permission -> @@ -108,6 +129,9 @@ internal class PermissionWatchmen( }.state } + private fun getPermissionEvent(permission: String) = + permissionEvents.filter { it.permission == permission } + /** * Watches for the permission events and updates appropriate state holders of permission */