Avoids flickering the screen when the update from Loading to Loaded happens on cached objects.

This commit is contained in:
Vitor Pamplona
2023-03-01 09:34:14 -05:00
parent e0596dc3b9
commit 459e503c8a
@@ -16,11 +16,14 @@ import kotlinx.coroutines.withContext
@Composable @Composable
fun UrlPreview(url: String, urlText: String, showUrlIfError: Boolean = true) { fun UrlPreview(url: String, urlText: String) {
var urlPreviewState by remember { mutableStateOf<UrlPreviewState>(UrlPreviewState.Loading) } val default = UrlCachedPreviewer.cache[url]?.let { UrlPreviewState.Loaded(it) } ?: UrlPreviewState.Loading
var urlPreviewState by remember { mutableStateOf(default) }
// Doesn't use a viewModel because of viewModel reusing issues (too many UrlPreview are created). // Doesn't use a viewModel because of viewModel reusing issues (too many UrlPreview are created).
LaunchedEffect(url) { LaunchedEffect(url) {
if (urlPreviewState == UrlPreviewState.Loading) {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
UrlCachedPreviewer.previewInfo(url, object : IUrlPreviewCallback { UrlCachedPreviewer.previewInfo(url, object : IUrlPreviewCallback {
override fun onComplete(urlInfo: UrlInfoItem) { override fun onComplete(urlInfo: UrlInfoItem) {
@@ -31,11 +34,13 @@ fun UrlPreview(url: String, urlText: String, showUrlIfError: Boolean = true) {
} }
override fun onFailed(throwable: Throwable) { override fun onFailed(throwable: Throwable) {
urlPreviewState = UrlPreviewState.Error("Error parsing preview for ${url}: ${throwable.message}") urlPreviewState =
UrlPreviewState.Error("Error parsing preview for ${url}: ${throwable.message}")
} }
}) })
} }
} }
}
Crossfade(targetState = urlPreviewState, animationSpec = tween(durationMillis = 100)) { state -> Crossfade(targetState = urlPreviewState, animationSpec = tween(durationMillis = 100)) { state ->
when (state) { when (state) {
@@ -43,12 +48,10 @@ fun UrlPreview(url: String, urlText: String, showUrlIfError: Boolean = true) {
UrlPreviewCard(url, state.previewInfo) UrlPreviewCard(url, state.previewInfo)
} }
else -> { else -> {
if (showUrlIfError) {
ClickableUrl(urlText, url) ClickableUrl(urlText, url)
} }
} }
} }
}
} }