Refine handleSnackbarMessage API (#676)

As per our offline convos during a PR review.
This commit is contained in:
Marco Romano 2023-06-26 16:29:50 +02:00 committed by GitHub
parent 59061f9e37
commit c5c9cd33da
4 changed files with 17 additions and 14 deletions

View file

@ -21,6 +21,7 @@ import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.remember
@ -28,27 +29,31 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.res.stringResource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* A global dispatcher of [SnackbarMessage] to be displayed in [Snackbar] via a [SnackbarHostState].
*/
class SnackbarDispatcher {
private val mutex = Mutex()
private val snackbarState = MutableStateFlow<SnackbarMessage?>(null)
val snackbarMessage: Flow<SnackbarMessage?> = snackbarState
private val _snackbarMessage = MutableStateFlow<SnackbarMessage?>(null)
val snackbarMessage: Flow<SnackbarMessage?> = _snackbarMessage.asStateFlow()
suspend fun post(message: SnackbarMessage) {
mutex.withLock {
snackbarState.update { message }
_snackbarMessage.update { message }
}
}
suspend fun clear() {
mutex.withLock {
snackbarState.update { null }
_snackbarMessage.update { null }
}
}
}
@ -59,10 +64,8 @@ val LocalSnackbarDispatcher = compositionLocalOf<SnackbarDispatcher> {
}
@Composable
fun handleSnackbarMessage(
snackbarDispatcher: SnackbarDispatcher
): SnackbarMessage? {
return snackbarDispatcher.snackbarMessage.collectAsState(initial = null).value
fun SnackbarDispatcher.collectSnackbarMessageAsState(): State<SnackbarMessage?> {
return snackbarMessage.collectAsState(initial = null)
}
@Composable