Skip to content

Instantly share code, notes, and snippets.

@AdrianoCelentano
Created February 7, 2022 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdrianoCelentano/c8522204cfcc7d15b108c9b52263df2a to your computer and use it in GitHub Desktop.
Save AdrianoCelentano/c8522204cfcc7d15b108c9b52263df2a to your computer and use it in GitHub Desktop.
PermissionFlow
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