Created
January 6, 2022 10:08
-
-
Save svenjacobs/cdcdd61998e6359b3fc0b4517536879b to your computer and use it in GitHub Desktop.
A composable inspired by ContentLoadingProgressBar
This file contains hidden or 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 androidx.compose.runtime.* | |
import androidx.compose.runtime.saveable.rememberSaveable | |
import kotlinx.coroutines.delay | |
import kotlin.time.Duration | |
import kotlin.time.ExperimentalTime | |
/** | |
* Inspired by View-based [ContentLoadingProgressBar](https://developer.android.com/reference/androidx/core/widget/ContentLoadingProgressBar). | |
* | |
* Waits `minDelayDuration` until contents of `loading` composable is shown when `isLoading` is | |
* true. Once loading is shown and `isLoading` becomes `false`, waits `minShowDuration` until | |
* content is shown to avoid flashes in the UI. If `isLoading` becomes `false` before | |
* `minDelayDuration` passes, the loading state is not shown at all. | |
* | |
* @param isLoading Whether loading or content state should be shown | |
* @param minDelayDuration Minimum delay until loading state is shown | |
* @param minShowDuration Minimum delay until loading state is dismissed if active | |
* @param loading Contents of loading state | |
* @param content Contents of content state | |
*/ | |
@Composable | |
@ExperimentalTime | |
fun ContentLoadingLayout( | |
isLoading: Boolean, | |
minDelayDuration: Duration = Duration.milliseconds(500), | |
minShowDuration: Duration = Duration.milliseconds(500), | |
loading: @Composable () -> Unit, | |
content: @Composable () -> Unit, | |
) { | |
var showLoading by rememberSaveable { mutableStateOf(false) } | |
var showContent by rememberSaveable { mutableStateOf(false) } | |
LaunchedEffect(isLoading) { | |
if (showContent) return@LaunchedEffect | |
if (isLoading && !showLoading) { | |
delay(minDelayDuration) | |
showLoading = true | |
} else if (!isLoading && showLoading) { | |
delay(minShowDuration) | |
showLoading = false | |
showContent = true | |
} else { | |
showContent = true | |
} | |
} | |
if (showLoading) { | |
loading() | |
} else if (showContent) { | |
content() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment