Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,8 @@ val androidTvModule = module {
}

// Content ViewModels
viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get(), get(), catalogLanguage = get()) }
// Starts hidden: the screens that show its rows report when they are on screen.
viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get(), get(), catalogLanguage = get(), startShown = false) }
viewModel { org.siloserver.silo.tv.ui.screens.home.TvUpcomingViewModel(get()) }
viewModel { RecommendationsViewModel(get(), catalogLanguage = get()) }
// The Requests page loads its view models when it composes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,21 +96,24 @@ fun TvHomeScreen(

// TV has no pull-to-refresh, so ON_RESUME is the only manual freshness
// path — refresh quietly whenever the user returns to Home (e.g. after
// finishing playback), complementing the realtime socket.
val lifecycleOwner = androidx.lifecycle.compose.LocalLifecycleOwner.current
androidx.compose.runtime.DisposableEffect(lifecycleOwner) {
val observer = androidx.lifecycle.LifecycleEventObserver { _, event ->
if (event == androidx.lifecycle.Lifecycle.Event.ON_RESUME) {
// The observer gets ON_RESUME as soon as it is added. On a new
// ViewModel that is while its own first load is still running,
// and a second full Home read would only supersede it.
if (shouldRefreshOnResume() && !viewModel.uiState.value.isLoading) {
viewModel.refreshFromRealtime()
}
}
// finishing playback), complementing the realtime socket. While Home is
// paused (the player, a detail page or another tab covers it) realtime
// updates wait, so a large Home is not re-read beside the player's buffer.
androidx.lifecycle.compose.LifecycleResumeEffect(viewModel) {
viewModel.onShown()
// The effect runs as soon as it is added. On a new ViewModel that is
// while its own first load is still running, and a second full Home
// read would only supersede it; the first load runs a waiting update.
if (shouldRefreshOnResume() && !viewModel.uiState.value.isLoading) {
viewModel.refreshFromRealtime()
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
onPauseOrDispose { viewModel.onHidden() }
}
// A return from a detail page skips the resume refresh until the shell has
// restored focus. An update that waited while Home was hidden runs then.
val refreshAllowed = shouldRefreshOnResume()
LaunchedEffect(refreshAllowed) {
if (refreshAllowed) viewModel.runPendingRealtimeRefresh()
}

when {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,14 @@ internal fun TvHomeSectionsEditor(

BackHandler(onBack = ::close)

// The editor lists Home's rows, so realtime and language updates reach
// them while it is open, as they do on Home itself.
androidx.lifecycle.compose.LifecycleResumeEffect(viewModel) {
viewModel.onShown()
viewModel.runPendingRealtimeRefresh()
onPauseOrDispose { viewModel.onHidden() }
}

LaunchedEffect(preferences, viewModel) {
preferences.refresh()
// The shell normally already owns populated Home state. A direct
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
Expand Down Expand Up @@ -69,10 +71,25 @@ class HomeViewModel(
private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(),
private val diagnostics: HomeDiagnosticsObserver = HomeDiagnosticsObserver.None,
private val catalogLanguage: org.siloserver.silo.domain.settings.CatalogLanguageRevision? = null,
/**
* Whether Home starts on screen. Android TV keeps one Home for the whole
* shell, which can come back on another tab, so it starts hidden and the
* screens that show its rows report [onShown] and [onHidden]; the phone
* never reports and stays shown.
*/
startShown: Boolean = true,
) : ViewModel() {

private var displayedOwner: AuthScopeSnapshot? = null

/**
* Realtime and language refreshes run only while Home is on screen; one
* that comes while it is hidden waits in [realtimeRefreshPending]. A full
* read of a large Home takes tens of megabytes, and on Android TV the
* player covering Home holds up to half the heap.
*/
private var shown = startShown

private suspend fun mayPublish(owner: AuthScopeSnapshot, generation: Int): Boolean {
val valid = sectionRepository.isHomeAuthorityCurrent(owner)
if (generation != fetchGeneration || !currentCoroutineContext().isActive) return false
Expand Down Expand Up @@ -100,9 +117,15 @@ class HomeViewModel(
catalogLanguage?.let { language ->
viewModelScope.launch {
// A metadata-language change re-localizes every card: re-read
// quietly. Unlike refreshFromRealtime this never skips, since a
// fetch already in flight still asked for the old language.
language.revision.drop(1).collectLatest {
// quietly. Unlike refreshFromRealtime this doesn't wait for a
// fetch already in flight, which still asked for the old
// language. A hidden Home re-reads when it is shown; that
// change is held back before collectLatest, so it never
// cancels a read that may be the one filling Home.
language.revision.drop(1).filter {
if (!shown) realtimeRefreshPending = true
shown
}.collectLatest {
val generation = fetchSections(HomeLoadTrigger.REALTIME)
if (generation == fetchGeneration) {
_uiState.update { it.copy(isRefreshing = false) }
Expand All @@ -118,13 +141,40 @@ class HomeViewModel(
}
}

/**
* Home's rows are on screen. A refresh that waited while they were hidden
* runs on [runPendingRealtimeRefresh] or the next [refreshFromRealtime].
*/
fun onShown() {
shown = true
}

/**
* Home's rows left the screen. Realtime and language refreshes wait for
* [onShown], and a realtime refresh still reading is dropped and waits too,
* unless Home is still empty: that read may be the one that fills it.
*/
fun onHidden() {
shown = false
if (realtimeRefreshInFlight && !_uiState.value.isLoading) {
realtimeRefreshJob?.cancel()
realtimeRefreshInFlight = false
realtimeRefreshPending = true
}
}

private var realtimeRefreshInFlight = false
private var realtimeRefreshJob: Job? = null

/** Bumped per realtime refresh, so a dropped one cannot clear its successor's in-flight flag. */
private var realtimeRefreshRun = 0

/**
* A realtime signal arrived while a fetch was running. That fetch may have
* been answered before the event behind the signal (an access change made
* after the request went out), so one more realtime refresh runs when it
* finishes.
* finishes. Also set by a realtime or language refresh that came while
* Home was hidden.
*/
private var realtimeRefreshPending = false

Expand All @@ -145,9 +195,10 @@ class HomeViewModel(
* Debounced realtime refetch: quiet (no spinner) and single-flight.
* Signals that arrive while a realtime or manual refresh is running are
* not raced against it; they collapse into one follow-up refresh after it.
* While Home is hidden they wait for it to be shown.
*/
fun refreshFromRealtime() {
if (realtimeRefreshInFlight || _uiState.value.isRefreshing) {
if (!shown || realtimeRefreshInFlight || _uiState.value.isRefreshing) {
Comment thread
Quick104 marked this conversation as resolved.
Resolved
realtimeRefreshPending = true
diagnostics.completed(
HomeLoadObservation(
Expand All @@ -163,18 +214,26 @@ class HomeViewModel(
return
}
realtimeRefreshInFlight = true
viewModelScope.launch {
// This read starts after every signal that is waiting.
realtimeRefreshPending = false
val run = ++realtimeRefreshRun
realtimeRefreshJob = viewModelScope.launch {
try {
fetchSections(HomeLoadTrigger.REALTIME)
} finally {
realtimeRefreshInFlight = false
if (run == realtimeRefreshRun) realtimeRefreshInFlight = false
}
runPendingRealtimeRefresh()
}
}

private fun runPendingRealtimeRefresh() {
if (!realtimeRefreshPending) return
/**
* Runs the realtime refresh that is waiting, if any. While the first load
* is still filling an empty Home it keeps waiting: that load runs it when
* it ends, instead of a second full read beside it.
*/
fun runPendingRealtimeRefresh() {
if (!realtimeRefreshPending || _uiState.value.isLoading) return
realtimeRefreshPending = false
refreshFromRealtime()
}
Expand All @@ -191,6 +250,7 @@ class HomeViewModel(
val owner = sectionRepository.captureHomeAuthority()
if (owner == null) {
if (fetchGeneration == bootstrapGeneration) fetchSections(HomeLoadTrigger.INITIAL)
runPendingRealtimeRefresh()
return@launch
}
if (!mayPublish(owner, bootstrapGeneration)) return@launch
Expand Down Expand Up @@ -233,6 +293,8 @@ class HomeViewModel(
_uiState.update { it.copy(isLoading = true, error = null) }
}
fetchSections(HomeLoadTrigger.INITIAL)
// A refresh that waited during the first load runs after it, not beside it.
runPendingRealtimeRefresh()
Comment thread
Quick104 marked this conversation as resolved.
Resolved
}
}

Expand Down Expand Up @@ -437,7 +499,8 @@ class HomeViewModel(
val result = mediaActions.performPersonalWrite(writeIntent)
if (!mediaActions.isCurrent(writeIntent)) return@launch
when (result) {
is ApiResult.Success -> refresh()
// A hidden Home re-reads when it is shown, not beside the player.
is ApiResult.Success -> if (shown) refresh() else realtimeRefreshPending = true
else -> _uiState.update { it.copy(sections = previous) }
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,15 @@ class HomeScreenV2Test {
private val local = object : UserItemStatePort by NoOpUserItemStatePort {
override suspend fun localPlaybackProgressForContent(contentIds: List<String>): Map<String, LocalPlaybackProgress> { overlayHook(); return emptyMap() }
}
private fun scenario(block: suspend TestScope.(HomeViewModel) -> Unit) = runTest {
// Each test report is a new change: a minute apart on this clock.
private var clockMs = 0L
private val accessChanges = AccessChangeSignals { clockMs }
private fun reportAccessChange() { clockMs += 60_000; accessChanges.reportAccessChanged() }
private val realtime = HomeRealtimeCoordinator(
object : HomeRealtimeClient { override fun connect() = kotlinx.coroutines.flow.emptyFlow<HomeRealtimeEvent>() },
tokens, accessChanges,
)
private fun scenario(startShown: Boolean = true, block: suspend TestScope.(HomeViewModel) -> Unit) = runTest {
val dispatcher = StandardTestDispatcher(testScheduler); Dispatchers.setMain(dispatcher)
val client = HttpClient(MockEngine(MockEngineConfig().apply {
this.dispatcher = dispatcher
Expand All @@ -62,7 +70,8 @@ class HomeScreenV2Test {
val store = ViewModelStore()
try {
val repository = SectionRepository(SectionApi(client, home = HomeSectionsV2Api(client, tokens, ApiV2Gate.Unrestricted, decodeDispatcher = dispatcher)))
val vm = HomeViewModel(repository, MediaActionsCoordinator(PersonalDataRepository(PersonalDataApi(client))), cache, local, catalogLanguage = language)
val vm = HomeViewModel(repository, MediaActionsCoordinator(PersonalDataRepository(PersonalDataApi(client))), cache, local,
homeRealtime = realtime, catalogLanguage = language, startShown = startShown)
store.put("home", vm); block(vm)
} finally { store.clear(); client.close(); Dispatchers.resetMain() }
}
Expand Down Expand Up @@ -124,4 +133,79 @@ class HomeScreenV2Test {
assertEquals("Latest language", vm.uiState.value.sections.single().items.single().title)
}

@Test fun hiddenHomeRunsOneDeferredRefreshWhenShown() = scenario(startShown = false) { vm ->
runCurrent(); assertEquals(1, listReads)
reportAccessChange(); advanceTimeBy(5_000); runCurrent()
language.changed(); runCurrent()
assertEquals(1, listReads, "a hidden Home must not re-read")
title = "New"; vm.onShown(); vm.runPendingRealtimeRefresh(); runCurrent()
assertEquals(2, listReads)
assertEquals("New", vm.uiState.value.sections.single().items.single().title)
vm.runPendingRealtimeRefresh(); runCurrent()
assertEquals(2, listReads, "the deferred refresh runs once")
}

@Test fun shownHomeRefreshesLiveAndStopsWhenHidden() = scenario { vm ->
runCurrent(); assertEquals(1, listReads)
reportAccessChange(); advanceTimeBy(5_000); runCurrent()
assertEquals(2, listReads)
vm.onHidden()
reportAccessChange(); advanceTimeBy(5_000); runCurrent()
assertEquals(2, listReads)
// The resume refresh covers the update that waited.
vm.onShown(); vm.refreshFromRealtime(); runCurrent()
assertEquals(3, listReads)
vm.runPendingRealtimeRefresh(); runCurrent()
assertEquals(3, listReads)
}

@Test fun hidingDropsARealtimeReadAndRunsItWhenShown() = scenario { vm ->
runCurrent(); assertEquals(1, listReads)
val gate = CompletableDeferred<Unit>(); listHook = { gate.await() }
title = "New"; reportAccessChange(); advanceTimeBy(5_000); runCurrent()
assertEquals(2, listReads)
vm.onHidden(); gate.complete(Unit); runCurrent()
assertEquals("Old", vm.uiState.value.sections.single().items.single().title, "the dropped read must not publish")
listHook = {}
vm.onShown(); vm.runPendingRealtimeRefresh(); runCurrent()
assertEquals(3, listReads)
assertEquals("New", vm.uiState.value.sections.single().items.single().title)
}

@Test fun hidingKeepsTheRealtimeReadThatFillsAnEmptyHome() = scenario { vm ->
val gate = CompletableDeferred<Unit>(); listHook = { gate.await() }
runCurrent(); assertTrue(vm.uiState.value.isLoading)
// This read supersedes the first load, so only it can fill Home.
reportAccessChange(); advanceTimeBy(5_000); runCurrent()
assertEquals(2, listReads)
vm.onHidden(); gate.complete(Unit); runCurrent()
assertFalse(vm.uiState.value.isLoading)
assertEquals("Old", vm.uiState.value.sections.single().items.single().title)
}

@Test fun hiddenLanguageChangeKeepsTheReadThatFillsAnEmptyHome() = scenario { vm ->
val gate = CompletableDeferred<Unit>(); listHook = { gate.await() }
runCurrent()
// This read supersedes the first load, so only it can fill Home.
language.changed(); runCurrent()
assertEquals(2, listReads)
vm.onHidden(); language.changed(); runCurrent()
gate.complete(Unit); runCurrent()
assertFalse(vm.uiState.value.isLoading)
assertEquals("Old", vm.uiState.value.sections.single().items.single().title)
listHook = {}; title = "New"
vm.onShown(); vm.runPendingRealtimeRefresh(); runCurrent()
assertEquals(3, listReads)
assertEquals("New", vm.uiState.value.sections.single().items.single().title)
}

@Test fun updateThatWaitedDuringFirstLoadRunsAfterIt() = scenario(startShown = false) { vm ->
val gate = CompletableDeferred<Unit>(); listHook = { gate.await() }
runCurrent(); assertEquals(1, listReads)
reportAccessChange(); advanceTimeBy(5_000); runCurrent()
vm.onShown(); vm.runPendingRealtimeRefresh(); runCurrent()
assertEquals(1, listReads, "no second read beside the first load")
listHook = {}; gate.complete(Unit); runCurrent()
assertEquals(2, listReads)
}
}
Loading