Skip to content

Commit

Permalink
perf: save explore contents to the view model
Browse files Browse the repository at this point in the history
Additionally add refresh button
  • Loading branch information
urFate committed May 20, 2024
1 parent 11101f9 commit 02bcecf
Show file tree
Hide file tree
Showing 5 changed files with 179 additions and 49 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package live.shirabox.shirabox.ui.component.navigation

import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
Expand All @@ -14,8 +19,16 @@ import live.shirabox.shirabox.ui.screen.profile.history.History

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShiraBoxNavHost(navController: NavHostController){
NavHost(navController = navController, startDestination = "main"){
fun ShiraBoxNavHost(navController: NavHostController) {
NavHost(
modifier = Modifier.fillMaxSize(),
navController = navController,
startDestination = "main",
enterTransition = { fadeIn(animationSpec = tween(400, delayMillis = 150)) },
exitTransition = { fadeOut(tween(delayMillis = 90)) },
popEnterTransition = { fadeIn(animationSpec = tween(400, delayMillis = 150)) },
popExitTransition = { fadeOut(tween(delayMillis = 90)) }
) {
navigation(BottomNavItems.Explore.route, "main") {
composable(BottomNavItems.Explore.route) { ExploreScreen(navController) }
composable(BottomNavItems.Favourites.route) { FavouritesScreen(navController) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package live.shirabox.shirabox.ui.screen.explore
import android.content.Intent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
Expand All @@ -19,14 +21,12 @@ import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
Expand All @@ -40,13 +40,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material3.fade
import com.google.accompanist.placeholder.material3.placeholder
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.emptyFlow
import live.shirabox.core.model.Content
import live.shirabox.core.model.ContentType
import live.shirabox.core.util.Util
import live.shirabox.data.catalog.shikimori.ShikimoriRepository
import live.shirabox.shirabox.R
import live.shirabox.shirabox.ui.activity.resource.ResourceActivity
import live.shirabox.shirabox.ui.component.general.BaseCard
Expand All @@ -57,49 +52,59 @@ import java.io.IOException

@Composable
fun BaseMediaScreen(
model: ExploreViewModel,
lazyListState: LazyListState
) {
val popularsPage = remember { mutableIntStateOf(1) }
val ongoingsListState = rememberLazyListState()

val contentObservationException = remember<MutableState<Exception?>> {
mutableStateOf(null)
}
val ongoingsStateFlow = model.ongoings.collectAsStateWithLifecycle(initialValue = emptyList())
val popularsStateFlow = model.populars.collectAsStateWithLifecycle(initialValue = emptyList())
val observationStatus = model.contentObservationStatus

val popularsStateFlow =
ShikimoriRepository.fetchPopulars(1..popularsPage.intValue, ContentType.ANIME)
.catch {
it.printStackTrace()
contentObservationException.value = it as Exception
emitAll(emptyFlow())
}
.collectAsStateWithLifecycle(initialValue = null)
val ongoingsStateFlow =
ShikimoriRepository.fetchOngoings(1, ContentType.ANIME)
.catch {
it.printStackTrace()
contentObservationException.value = it as Exception
emitAll(emptyFlow())
}
.collectAsStateWithLifecycle(initialValue = null)
val isReady = remember(popularsStateFlow.value, ongoingsStateFlow.value, observationStatus.value) {
(popularsStateFlow.value.isNotEmpty() && ongoingsStateFlow.value.isNotEmpty()) && observationStatus.value.status == ExploreViewModel.Status.Success
}

val isReady = remember(popularsStateFlow.value, ongoingsStateFlow.value) {
(popularsStateFlow.value != null && ongoingsStateFlow.value != null)
LaunchedEffect(null) {
if(observationStatus.value.status == ExploreViewModel.Status.Success) {
model.populars.emit(model.populars.value.subList(0, 16))
}
if(observationStatus.value.status != ExploreViewModel.Status.Success) {
model.fetchOngoings()
model.fetchPopulars()
}
}
LaunchedEffect(model.popularsPage.intValue) {
if(isReady) model.fetchPopulars()
}

AnimatedVisibility(visible = contentObservationException.value != null, enter = fadeIn()) {
AnimatedVisibility(
visible = observationStatus.value.status == ExploreViewModel.Status.Failure,
enter = fadeIn(),
exit = fadeOut()
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
when (contentObservationException.value) {
is IOException -> DespondencyEmoticon(text = stringResource(id = R.string.no_internet_connection_variant))
else -> ScaredEmoticon(text = stringResource(id = R.string.no_contents))
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
when (observationStatus.value.exception) {
is IOException -> DespondencyEmoticon(text = stringResource(id = R.string.no_internet_connection_variant))
else -> ScaredEmoticon(text = stringResource(id = R.string.no_contents))
}

OutlinedButton(onClick = { model.refresh() }) {
Text(stringResource(id = R.string.refresh))
}
}
}
}

if(contentObservationException.value != null) return
if(observationStatus.value.status == ExploreViewModel.Status.Failure) return

Column(
verticalArrangement = Arrangement.spacedBy(16.dp)
Expand All @@ -120,7 +125,7 @@ fun BaseMediaScreen(

OngoingsRow(
isReady = isReady,
contents = ongoingsStateFlow.value ?: emptyList(),
contents = ongoingsStateFlow.value,
ongoingsListState = ongoingsListState
)
}
Expand All @@ -144,13 +149,11 @@ fun BaseMediaScreen(
fontWeight = FontWeight(500)
)

PopularsGrid(
contents = popularsStateFlow.value ?: emptyList()
)
PopularsGrid(contents = popularsStateFlow.value)
}

LaunchedEffect(lazyListState.canScrollForward) {
if(!lazyListState.canScrollForward && isReady) popularsPage.intValue += 1
if(!lazyListState.canScrollForward && isReady) model.popularsPage.intValue += 1
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,40 +1,74 @@
package live.shirabox.shirabox.ui.screen.explore

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import live.shirabox.core.util.Util
import live.shirabox.shirabox.ui.component.top.TopBar


@OptIn(ExperimentalMaterialApi::class)
@ExperimentalMaterial3Api
@Composable
fun ExploreScreen(navController: NavController) {
fun ExploreScreen(
navController: NavController,
model: ExploreViewModel = viewModel(factory = Util.viewModelFactory {
ExploreViewModel()
})
) {

val lazyListState = rememberLazyListState()
val pullRefreshState = rememberPullRefreshState(model.refreshing.value, { model.refresh() })

Scaffold(
modifier = Modifier.pullRefresh(pullRefreshState),
snackbarHost = { AppUpdateSnackbarHost() },
contentWindowInsets = WindowInsets(0.dp)
) {
LazyColumn(
Box (
modifier = Modifier
.fillMaxSize()
.padding(it),
state = lazyListState,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
item { TopBar(navController) }
item { BaseMediaScreen(lazyListState = lazyListState) }
contentAlignment = Alignment.TopCenter
){
LazyColumn(
modifier = Modifier
.fillMaxSize()
.zIndex(1f),
state = lazyListState,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
item { TopBar(navController) }
item { BaseMediaScreen(model = model, lazyListState = lazyListState) }
}

PullRefreshIndicator(
modifier = Modifier.zIndex(2f),
refreshing = model.refreshing.value,
state = pullRefreshState,
scale = true,
contentColor = MaterialTheme.colorScheme.primary
)
}
}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package live.shirabox.shirabox.ui.screen.explore

import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch
import live.shirabox.core.model.Content
import live.shirabox.core.model.ContentType
import live.shirabox.data.catalog.shikimori.ShikimoriRepository

class ExploreViewModel : ViewModel() {
val populars = MutableStateFlow(emptyList<Content>())
val ongoings = MutableStateFlow(emptyList<Content>())

val contentObservationStatus = mutableStateOf(ObservationStatus(Status.Loading))
val popularsPage = mutableIntStateOf(1)
val refreshing = mutableStateOf(false)

fun fetchOngoings() {
viewModelScope.launch(Dispatchers.IO) {
ShikimoriRepository.fetchOngoings(1, ContentType.ANIME)
.catch {
it.printStackTrace()
contentObservationStatus.value = ObservationStatus(Status.Failure, it as Exception)
emitAll(emptyFlow())
}.collectLatest {
ongoings.emit(it)
contentObservationStatus.value = ObservationStatus(Status.Success)
}
}
}

fun fetchPopulars() {
viewModelScope.launch(Dispatchers.IO) {
ShikimoriRepository.fetchPopulars(1..popularsPage.intValue, ContentType.ANIME)
.catch {
it.printStackTrace()
contentObservationStatus.value = ObservationStatus(Status.Failure, it as Exception)
emitAll(emptyFlow())
}.onCompletion {
delay(1000L)
refreshing.value = false
}
.collectLatest {
populars.emit(it)
contentObservationStatus.value = ObservationStatus(Status.Success)
}
}
}

fun refresh() {
viewModelScope.launch(Dispatchers.IO) {
popularsPage.intValue = 1
contentObservationStatus.value = ObservationStatus(Status.Loading)
refreshing.value = true

fetchOngoings()
fetchPopulars()
}
}

data class ObservationStatus(
val status: Status,
val exception: Exception? = null
)

enum class Status {
Loading, Success, Failure
}
}
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
<string name="notifications">Уведомления</string>
<string name="today">Сегодня</string>
<string name="update_available">Доступно обновление приложения!</string>
<string name="refresh">Попробовать снова</string>


<!--
Expand Down

0 comments on commit 02bcecf

Please sign in to comment.