Created
February 7, 2022 11:26
-
-
Save AdrianoCelentano/c8522204cfcc7d15b108c9b52263df2a to your computer and use it in GitHub Desktop.
PermissionFlow
This file contains 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
import android.content.Context | |
import android.content.pm.PackageManager | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleEventObserver | |
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.ProcessLifecycleOwner | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.channels.awaitClose | |
import kotlinx.coroutines.channels.trySendBlocking | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.callbackFlow | |
import kotlinx.coroutines.flow.distinctUntilChanged | |
import kotlinx.coroutines.flow.filter | |
import kotlinx.coroutines.flow.flowOn | |
import kotlinx.coroutines.flow.map | |
import kotlinx.coroutines.flow.onStart | |
fun permissionFlow( | |
context: Context, | |
permission: String | |
): Flow<Boolean> { | |
fun hasPermission() = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED | |
return ProcessLifecycleOwner.get().lifecycleEventFlow() | |
.filter { it == Lifecycle.Event.ON_RESUME } | |
.map { hasPermission() } | |
.onStart { emit(hasPermission()) } | |
.distinctUntilChanged() | |
} | |
private fun LifecycleOwner.lifecycleEventFlow(): Flow<Lifecycle.Event> { | |
return callbackFlow { | |
val observer = LifecycleEventObserver { _, event -> trySendBlocking(event) } | |
lifecycle.addObserver(observer) | |
awaitClose { lifecycle.removeObserver(observer) } | |
}.flowOn(Dispatchers.Main) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment