diff --git a/.gitignore b/.gitignore index 230dce7..1804aec 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,25 @@ package-lock.json keystore.properties .gradle_user_home/ +.jules/ +.kotlin/ + +# More AI / agent files (local only) +CLAUDE.md +CLAUDE.local.md +.claude/ +AGENTS.md +GEMINI.md +QWEN.md +.pi/ +.qwen/ +.opencode/ +.windsurf/ +.windsurfrules +.aider* +.continue/ +.codex/ +.github/copilot-instructions.md +outline.md +Pdoc/ +pdocs/ diff --git a/.jules/bolt.md b/.jules/bolt.md deleted file mode 100644 index 8f342ab..0000000 --- a/.jules/bolt.md +++ /dev/null @@ -1,5 +0,0 @@ -## 2024-05-24 - Started - -## 2024-05-24 - O(N) Iteration in Cache Size Calculation -**Learning:** Calculating dynamic capacity dynamically via `store.values.sumOf { it.sizeBytes }` effectively incurs an O(N) cost on every `put` because it runs when `trimToCapacity()` calls `dynamicCapacity`. When cache sizes get large, this causes O(N²) overall insertion performance and UI stutters. -**Action:** Use an `AtomicLong` (O(1)) to track the running sum of cache size instead of dynamically iterating through the entire collection. diff --git a/.jules/palette.md b/.jules/palette.md deleted file mode 100644 index a021571..0000000 --- a/.jules/palette.md +++ /dev/null @@ -1,6 +0,0 @@ -## 2024-05-18 - MinimalButton Accessibility -**Learning:** Custom clickable components without a specific Semantic Role assigned will not be announced correctly by screen readers. Applying `role = Role.Button` to the `clickable` modifier ensures it is recognized correctly as a button. -**Action:** Add `role = Role.Button` to the `clickable` modifier for custom interactive button components. -## 2024-05-18 - Redundant Icon Content Descriptions -**Learning:** Adding `contentDescription` to icons that are directly adjacent to `Text` components containing the same wording is an anti-pattern. Screen readers will announce the information twice (e.g., "Liked, Liked"), creating a noisy experience. Icons in this context should remain decorative (`contentDescription = null`). -**Action:** Verify if text alternatives exist near visual elements before assigning a `contentDescription` to avoid duplicate screen reader announcements. diff --git a/.jules/sentinel.md b/.jules/sentinel.md deleted file mode 100644 index dcfee25..0000000 --- a/.jules/sentinel.md +++ /dev/null @@ -1,4 +0,0 @@ -## 2024-05-27 - Implement CSRF Protection for OAuth -**Vulnerability:** OAuth state parameter used a predictable `System.currentTimeMillis()` value, vulnerable to CSRF attacks. -**Learning:** Always use a cryptographically secure random value for OAuth state parameter and persist it across process boundaries using shared preferences or similar mechanisms to verify during the callback. -**Prevention:** Follow OAuth 2.0 security guidelines and utilize `java.security.SecureRandom` or UUIDs to generate state parameters, ensuring they are verified in the callback process. diff --git a/app/src/main/java/com/example/reddittube/Navigation.kt b/app/src/main/java/com/example/reddittube/Navigation.kt index e2d3077..d592d98 100644 --- a/app/src/main/java/com/example/reddittube/Navigation.kt +++ b/app/src/main/java/com/example/reddittube/Navigation.kt @@ -5,7 +5,6 @@ import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn -import androidx.compose.animation.scaleOut import androidx.compose.animation.togetherWith import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable @@ -37,9 +36,17 @@ fun MainNavigation() { NavDisplay( backStack = backStack, onBack = { backStack.removeLastOrNull() }, + // Short, minimal transitions. Pop and predictive-back must be set too: the library + // defaults are 700ms slides, which made going back from the player feel slow. transitionSpec = { - (fadeIn(animationSpec = tween(220, easing = FastOutSlowInEasing)) + scaleIn(initialScale = 0.95f, animationSpec = tween(240, easing = FastOutSlowInEasing))) - .togetherWith(fadeOut(animationSpec = tween(180, easing = FastOutSlowInEasing)) + scaleOut(targetScale = 0.97f, animationSpec = tween(180, easing = FastOutSlowInEasing))) + (fadeIn(tween(160, easing = FastOutSlowInEasing)) + scaleIn(tween(160, easing = FastOutSlowInEasing), initialScale = 0.97f)) + .togetherWith(fadeOut(tween(120))) + }, + popTransitionSpec = { + fadeIn(tween(140)).togetherWith(fadeOut(tween(120))) + }, + predictivePopTransitionSpec = { + fadeIn(tween(140)).togetherWith(fadeOut(tween(120))) }, entryProvider = entryProvider { diff --git a/app/src/main/java/com/example/reddittube/data/DataRepository.kt b/app/src/main/java/com/example/reddittube/data/DataRepository.kt index 6d0cda0..af61da5 100644 --- a/app/src/main/java/com/example/reddittube/data/DataRepository.kt +++ b/app/src/main/java/com/example/reddittube/data/DataRepository.kt @@ -404,7 +404,8 @@ class DefaultDataRepository(private val context: Context) : DataRepository { var result = performOAuthRequest(sub, token, sort, feed) if (result.isEmpty()) { val freshToken = RedditOAuthHelper.getOrFetchAccessToken(context) - if (freshToken != null) { + // Retry only with a different token: the cached one just returned nothing + if (freshToken != null && freshToken != token) { result = performOAuthRequest(sub, freshToken, sort, feed) } } @@ -440,11 +441,17 @@ class DefaultDataRepository(private val context: Context) : DataRepository { put("subscribed", mutableMapOf()) } + // Written from parallel per-subreddit IO coroutines: every access goes through this lock + // (plain maps, since cursors can be null and ConcurrentHashMap rejects null values). private fun feedMap(feed: String): MutableMap = afterMaps.getOrPut(feed) { mutableMapOf() } - override fun getAfterMap(feed: String): Map = feedMap(feed).toMap() + private fun setAfter(feed: String, subreddit: String, after: String?) = synchronized(afterMaps) { + feedMap(feed)[subreddit] = after + } - override fun saveAfterMap(map: Map, feed: String) { + override fun getAfterMap(feed: String): Map = synchronized(afterMaps) { feedMap(feed).toMap() } + + override fun saveAfterMap(map: Map, feed: String) = synchronized(afterMaps) { if (map.isEmpty()) { feedMap(feed).clear() } else { @@ -689,7 +696,7 @@ class DefaultDataRepository(private val context: Context) : DataRepository { } } - feedMap(feed)[subreddit] = after + setAfter(feed, subreddit, after) Log.i("RedditRepository", "r/$subreddit parsed ${list.size} videos, after=$after") return list } diff --git a/app/src/main/java/com/example/reddittube/ui/main/HomeScreen.kt b/app/src/main/java/com/example/reddittube/ui/main/HomeScreen.kt index ee18ba2..b8a8772 100644 --- a/app/src/main/java/com/example/reddittube/ui/main/HomeScreen.kt +++ b/app/src/main/java/com/example/reddittube/ui/main/HomeScreen.kt @@ -238,6 +238,7 @@ fun HomeScreen( likedIds = likedIds, onLike = viewModel::toggleLike, onCommentClick = { post -> activeCommentPost = post }, + onScrollDirection = { bottomBarVisible = !it }, modifier = Modifier.fillMaxSize() ) 3 -> LibraryPage( @@ -393,9 +394,9 @@ fun HomeScreen( ) { // Ultra-Smooth, Minimalist Monochrome Floating Pill Navigation Dock AnimatedVisibility( - visible = bottomBarVisible || horizontalPagerState.currentPage == 2 || horizontalPagerState.currentPage == 3 || horizontalPagerState.currentPage == 4, - enter = slideInVertically(initialOffsetY = { it * 2 }) + fadeIn(tween(180)), - exit = slideOutVertically(targetOffsetY = { it * 2 }) + fadeOut(tween(180)) + visible = bottomBarVisible || horizontalPagerState.currentPage == 3 || horizontalPagerState.currentPage == 4, + enter = slideInVertically(tween(180), initialOffsetY = { it * 2 }) + fadeIn(tween(150)), + exit = slideOutVertically(tween(150), targetOffsetY = { it * 2 }) + fadeOut(tween(120)) ) { FloatingPillNavBar( selectedTab = NavTabItem.entries[horizontalPagerState.currentPage], diff --git a/app/src/main/java/com/example/reddittube/ui/main/MainScreenViewModel.kt b/app/src/main/java/com/example/reddittube/ui/main/MainScreenViewModel.kt index f7bf121..902008b 100644 --- a/app/src/main/java/com/example/reddittube/ui/main/MainScreenViewModel.kt +++ b/app/src/main/java/com/example/reddittube/ui/main/MainScreenViewModel.kt @@ -14,8 +14,12 @@ import com.lean.reddittube.data.RedditError import com.lean.reddittube.data.RedditPost import com.lean.reddittube.utils.toJson import com.lean.reddittube.utils.toRedditPost +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import kotlinx.coroutines.isActive import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -43,7 +47,11 @@ enum class SortOption(val value: String, val label: String, val description: Str TOP_ALL("top?t=all", "Top (All Time)", "Greatest all-time highest voted videos") } -class MainScreenViewModel(private val dataRepository: DataRepository) : ViewModel() { +class MainScreenViewModel( + private val dataRepository: DataRepository, + // Off-Main work (JSON for prefs/feed caches); tests pass their test dispatcher + private val backgroundDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.Default +) : ViewModel() { private val _exploreState = MutableStateFlow(MainScreenUiState.Loading) val exploreState: StateFlow = _exploreState.asStateFlow() @@ -54,6 +62,14 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode const val DEFAULT_EXPLORE_FEED = "videos+tiktokcringe+unexpected+youtubehaiku+damnthatsinteresting+nextfuckinglevel+idiotsincars+publicfreakout+holdmybeer+maybemaybemaybe+gaming+contagiouslaughter+oddlysatisfying" private const val WATCHED_CAP = 1000 private const val LIKED_CAP = 1000 + private const val FEED_CACHE_KEYS = "feed_cache_keys" + private const val FEED_CACHE_KEEP = 12 + private const val SEARCH_CACHE_MAX = 30 + + // Search result caches are only touched on Main; bounded so a long session can't grow them forever + private fun lruMap(max: Int): MutableMap = object : LinkedHashMap(16, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?) = size > max + } private const val CACHE_STALE_DURATION_MS = 5 * 60 * 1000L // 5 minutes } @@ -93,7 +109,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode private var inSubredditSearchAfter: String? = null private var currentInSubredditSearchQuery: String = "" private var currentInSubredditSearchTarget: String = "" - private val inSubredditSearchCache = mutableMapOf() + private val inSubredditSearchCache = lruMap(SEARCH_CACHE_MAX) // ponytail: list + index opened from the browse/home grid, played by PlayerScreen private val _playerList = MutableStateFlow>(emptyList()) @@ -218,12 +234,21 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode fun getLikedPosts(): List = likedOrder.asReversed().mapNotNull { likedPostsMap[it] } + // Persistence: snapshot on Main (cheap), serialize up to 1000 posts to JSON off Main. + // A single-threaded dispatcher keeps writes in call order. + private val persistDispatcher = backgroundDispatcher.limitedParallelism(1) + private fun saveLiked() { - prefs.edit() - .putStringSet("liked_ids", likedIdsSet.toSet()) - .putString("liked_order", org.json.JSONArray(likedOrder).toString()) - .putString("liked_posts", org.json.JSONArray().apply { likedPostsMap.values.forEach { put(it.toJson()) } }.toString()) - .apply() + val ids = likedIdsSet.toSet() + val order = likedOrder.toList() + val posts = likedPostsMap.values.toList() + viewModelScope.launch(persistDispatcher) { + prefs.edit() + .putStringSet("liked_ids", ids) + .putString("liked_order", org.json.JSONArray(order).toString()) + .putString("liked_posts", org.json.JSONArray().apply { posts.forEach { put(it.toJson()) } }.toString()) + .apply() + } } private fun showError(e: Throwable) { @@ -239,13 +264,14 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode private data class PagedVideoCache(val posts: List, val after: String?) private var searchJob: Job? = null - private val searchCache = ConcurrentHashMap() + private val searchCache = lruMap(SEARCH_CACHE_MAX) private var subredditSearchAfter: String? = null private var currentSubredditSearchQuery: String = "" fun searchSubreddits(query: String, immediate: Boolean = false) { val trimmed = query.trim().lowercase().removePrefix("r/") if (trimmed.length < 2) { + searchJob?.cancel() _searchResults.value = emptyList() _isSubredditSearching.value = false subredditSearchAfter = null @@ -255,6 +281,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode currentSubredditSearchQuery = trimmed val cached = searchCache[trimmed] if (cached != null) { + searchJob?.cancel() _searchResults.value = cached.subreddits subredditSearchAfter = cached.after _isSubredditSearching.value = false @@ -273,10 +300,12 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode subredditSearchAfter = result.after _searchResults.value = result.subreddits } + } catch (e: CancellationException) { + throw e } catch (_: Exception) { _searchResults.value = emptyList() } finally { - _isSubredditSearching.value = false + if (isActive) _isSubredditSearching.value = false } } } @@ -307,7 +336,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode } private var videoSearchJob: Job? = null - private val videoSearchCache = ConcurrentHashMap() + private val videoSearchCache = lruMap(SEARCH_CACHE_MAX) private var videoSearchAfter: String? = null private var currentVideoSearchQuery: String = "" private var currentVideoSearchSort: String = "relevance" @@ -317,6 +346,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode val trimmed = query.trim() val cleanSub = subreddit?.trim()?.removePrefix("r/")?.takeIf { it.isNotEmpty() } if (trimmed.length < 2) { + videoSearchJob?.cancel() _videoSearchResults.value = emptyList() _isVideoSearching.value = false videoSearchAfter = null @@ -330,6 +360,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode val cacheKey = if (cleanSub != null) "$cleanSub:$trimmed:$sort" else "$trimmed:$sort" val cached = videoSearchCache[cacheKey] if (cached != null) { + videoSearchJob?.cancel() _videoSearchResults.value = cached.posts videoSearchAfter = cached.after _isVideoSearching.value = false @@ -349,10 +380,12 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode videoSearchAfter = afterCursor _videoSearchResults.value = result.posts } + } catch (e: CancellationException) { + throw e } catch (_: Exception) { _videoSearchResults.value = emptyList() } finally { - _isVideoSearching.value = false + if (isActive) _isVideoSearching.value = false } } } @@ -396,6 +429,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode val trimmed = query.trim() val cleanSub = subreddit.trim().removePrefix("r/") if (trimmed.length < 2 || cleanSub.isEmpty()) { + inSubredditSearchJob?.cancel() _subredditSearchResults.value = emptyList() _isSubredditSearching.value = false inSubredditSearchAfter = null @@ -408,6 +442,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode val cacheKey = "$cleanSub:$trimmed:$sort" val cached = inSubredditSearchCache[cacheKey] if (cached != null) { + inSubredditSearchJob?.cancel() _subredditSearchResults.value = cached.posts inSubredditSearchAfter = cached.after _isSubredditSearching.value = false @@ -427,10 +462,12 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode inSubredditSearchAfter = afterCursor _subredditSearchResults.value = result.posts } + } catch (e: CancellationException) { + throw e } catch (_: Exception) { _subredditSearchResults.value = emptyList() } finally { - _isSubredditSearching.value = false + if (isActive) _isSubredditSearching.value = false } } } @@ -488,12 +525,20 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode sizeEstimator = { list -> (list.size * 512L).coerceAtLeast(1024L) } ) + // Feed jobs: a refresh cancels the previous refresh and any loadMore of the same feed, + // so a slow older response cannot overwrite the newer feed. + private var exploreJob: Job? = null + private var subscribedJob: Job? = null + private val loadMoreJobs = mutableMapOf() + fun refreshExplore(query: String = exploreQuery, forceRefresh: Boolean = false) { if (query != exploreQuery) { setSubredditSearchActive(false) } exploreQuery = query - viewModelScope.launch { + exploreJob?.cancel() + loadMoreJobs.remove("explore")?.cancel() + exploreJob = viewModelScope.launch { val sortVal = currentSort.value val cacheKey = "explore_${query}_$sortVal" val cached = (memoryFeedCache[cacheKey] ?: loadExploreCache(query, sortVal).filter { !isHidden(it.id) }).distinctBy { it.id } @@ -523,6 +568,8 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode _exploreState.value = MainScreenUiState.Error(RedditError.NoVideosFound(query)) } } + } catch (e: CancellationException) { + throw e } catch (e: RedditError) { showError(e) if (_exploreState.value !is MainScreenUiState.Success) { @@ -539,7 +586,9 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode fun refreshSubscribed(query: String, forceRefresh: Boolean = false) { subscribedQuery = query - viewModelScope.launch { + subscribedJob?.cancel() + loadMoreJobs.remove("subscribed")?.cancel() + subscribedJob = viewModelScope.launch { if (query.isEmpty()) { _subscribedState.value = MainScreenUiState.Error(RedditError.Unknown("No subscribed subreddits. Use the search icon to add subreddits.")) return@launch @@ -573,6 +622,8 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode _subscribedState.value = MainScreenUiState.Error(RedditError.NoVideosFound(query)) } } + } catch (e: CancellationException) { + throw e } catch (e: RedditError) { showError(e) if (_subscribedState.value !is MainScreenUiState.Success) { @@ -596,7 +647,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode val afterMap = dataRepository.getAfterMap(feed) if (afterMap.isNotEmpty() && afterMap.values.all { it == null }) return // no more pages anywhere - viewModelScope.launch { + loadMoreJobs[feed] = viewModelScope.launch { // set loading flag if (isExplore) { _exploreState.value = current.copy(isLoadingMore = true) @@ -617,6 +668,8 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode _subscribedState.value = MainScreenUiState.Success(updated, isLoadingMore = false) } } + } catch (e: CancellationException) { + throw e } catch (e: Exception) { showError(e) if (isExplore) { @@ -664,12 +717,18 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode } private fun saveWatched() { - prefs.edit() - .putStringSet("watched_ids", watchedIds.toSet()) - .putString("watched_order", org.json.JSONArray(watchedOrder).toString()) - .putString("watched_titles", org.json.JSONObject(watchedTitles).toString()) - .putString("watched_posts", org.json.JSONArray().apply { watchedPosts.values.forEach { put(it.toJson()) } }.toString()) - .apply() + val ids = watchedIds.toSet() + val order = watchedOrder.toList() + val titles = watchedTitles.toMap() + val posts = watchedPosts.values.toList() + viewModelScope.launch(persistDispatcher) { + prefs.edit() + .putStringSet("watched_ids", ids) + .putString("watched_order", org.json.JSONArray(order).toString()) + .putString("watched_titles", org.json.JSONObject(titles).toString()) + .putString("watched_posts", org.json.JSONArray().apply { posts.forEach { put(it.toJson()) } }.toString()) + .apply() + } } fun getWatchedPosts(): List { @@ -692,29 +751,38 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode return dataRepository.fetchPostComments(subreddit, postId) } - private fun saveExploreCache(query: String, sort: String, posts: List) { - val arr = org.json.JSONArray().apply { posts.take(60).forEach { put(it.toJson()) } } - prefs.edit().putString("explore_cache_${query}_$sort", arr.toString()).apply() - } - - private fun loadExploreCache(query: String, sort: String): List { - val str = prefs.getString("explore_cache_${query}_$sort", null) ?: return emptyList() - return try { - val arr = org.json.JSONArray(str) - (0 until arr.length()).mapNotNull { arr.getJSONObject(it).toRedditPost() }.distinctBy { it.id } - } catch (_: Exception) { - emptyList() + private fun saveExploreCache(query: String, sort: String, posts: List) = + saveFeedCache("explore_cache_${query}_$sort", posts) + + private suspend fun loadExploreCache(query: String, sort: String): List = + loadFeedCache("explore_cache_${query}_$sort") + + private fun saveSubscribedCache(query: String, sort: String, posts: List) = + saveFeedCache("subscribed_cache_${query}_$sort", posts) + + // Every visited feed (subreddit x sort) used to add a key forever, and SharedPreferences keeps + // the whole file in memory and rewrites it on each apply(): track keys and drop the oldest. + private fun saveFeedCache(key: String, posts: List) { + val snapshot = posts.take(60) + viewModelScope.launch(persistDispatcher) { + val arr = org.json.JSONArray().apply { snapshot.forEach { put(it.toJson()) } } + // First run with tracking: adopt the untracked keys older versions left behind + val known = if (prefs.contains(FEED_CACHE_KEYS)) runCatching { + org.json.JSONArray(prefs.getString(FEED_CACHE_KEYS, "[]") ?: "[]").let { a -> (0 until a.length()).map { a.getString(it) } } + }.getOrDefault(emptyList()) else prefs.all.keys.filter { it.startsWith("explore_cache_") || it.startsWith("subscribed_cache_") } + val keys = known.filter { it != key } + key + val evicted = keys.dropLast(FEED_CACHE_KEEP) + val editor = prefs.edit() + .putString(key, arr.toString()) + .putString(FEED_CACHE_KEYS, org.json.JSONArray(keys.takeLast(FEED_CACHE_KEEP)).toString()) + evicted.forEach { editor.remove(it) } + editor.apply() } } - private fun saveSubscribedCache(query: String, sort: String, posts: List) { - val arr = org.json.JSONArray().apply { posts.take(60).forEach { put(it.toJson()) } } - prefs.edit().putString("subscribed_cache_${query}_$sort", arr.toString()).apply() - } - - private fun loadSubscribedCache(query: String, sort: String): List { - val str = prefs.getString("subscribed_cache_${query}_$sort", null) ?: return emptyList() - return try { + private suspend fun loadFeedCache(key: String): List = withContext(backgroundDispatcher) { + val str = prefs.getString(key, null) ?: return@withContext emptyList() + try { val arr = org.json.JSONArray(str) (0 until arr.length()).mapNotNull { arr.getJSONObject(it).toRedditPost() }.distinctBy { it.id } } catch (_: Exception) { @@ -722,4 +790,7 @@ class MainScreenViewModel(private val dataRepository: DataRepository) : ViewMode } } + private suspend fun loadSubscribedCache(query: String, sort: String): List = + loadFeedCache("subscribed_cache_${query}_$sort") + } diff --git a/app/src/main/java/com/example/reddittube/ui/main/SearchPage.kt b/app/src/main/java/com/example/reddittube/ui/main/SearchPage.kt index f8776ed..59d3b3b 100644 --- a/app/src/main/java/com/example/reddittube/ui/main/SearchPage.kt +++ b/app/src/main/java/com/example/reddittube/ui/main/SearchPage.kt @@ -26,6 +26,10 @@ import androidx.compose.material.icons.outlined.Subscriptions import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.nestedscroll.NestedScrollConnection +import androidx.compose.ui.input.nestedscroll.NestedScrollSource +import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -99,6 +103,7 @@ fun SearchPage( likedIds: Set = emptySet(), onLike: (RedditPost) -> Unit = {}, onCommentClick: (RedditPost) -> Unit = {}, + onScrollDirection: (Boolean) -> Unit = {}, modifier: Modifier = Modifier ) { val context = LocalContext.current @@ -175,13 +180,34 @@ fun SearchPage( POPULAR_SUBREDDITS.filter { !currentSubscribed.contains(it.lowercase()) } } + // Auto-hide the search header (and the nav dock via onScrollDirection) while scrolling down + var headerVisible by remember { mutableStateOf(true) } + LaunchedEffect(selectedTab, searchQuery) { headerVisible = true } + LaunchedEffect(headerVisible) { onScrollDirection(!headerVisible) } + val headerScrollConnection = remember { + object : NestedScrollConnection { + override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { + if (available.y < -6f) headerVisible = false + else if (available.y > 6f) headerVisible = true + return Offset.Zero + } + } + } + Column( modifier = modifier .fillMaxSize() .background(Color.Black) .statusBarsPadding() .padding(top = TopBarHeight + 2.dp) + .nestedScroll(headerScrollConnection) ) { + AnimatedVisibility( + visible = headerVisible, + enter = fadeIn(tween(180)) + expandVertically(tween(180)), + exit = fadeOut(tween(150)) + shrinkVertically(tween(150)) + ) { + Column { // Top Distinctive Search Bar Surface( modifier = Modifier @@ -397,6 +423,8 @@ fun SearchPage( } } } + } + } // Tab Content when (selectedTab) { @@ -409,7 +437,7 @@ fun SearchPage( total > 0 && lastVisible >= total - 3 } } - LaunchedEffect(isNearSubEnd) { + LaunchedEffect(isNearSubEnd, cleanQuery, isSubredditSearchingMore) { if (isNearSubEnd && cleanQuery.isNotBlank() && !isSubredditSearchingMore) { onLoadMoreSubreddits() } @@ -967,7 +995,7 @@ fun SearchPage( total > 0 && lastVisible >= total - 4 } } - LaunchedEffect(isNearVideoEnd) { + LaunchedEffect(isNearVideoEnd, searchQuery, isVideoSearchingMore, isVideoSearching) { if (isNearVideoEnd && searchQuery.isNotBlank() && !isVideoSearchingMore && !isVideoSearching) { onLoadMoreVideos() } diff --git a/app/src/main/java/com/example/reddittube/ui/main/VideoPage.kt b/app/src/main/java/com/example/reddittube/ui/main/VideoPage.kt index 4bc12e8..cf434a9 100644 --- a/app/src/main/java/com/example/reddittube/ui/main/VideoPage.kt +++ b/app/src/main/java/com/example/reddittube/ui/main/VideoPage.kt @@ -31,7 +31,9 @@ import androidx.compose.animation.scaleOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.animation.core.tween +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.lifecycle.Lifecycle @@ -356,6 +358,11 @@ fun VideoPage( val activity = context as? Activity val audioManager = remember { context.getSystemService(Context.AUDIO_SERVICE) as AudioManager } + // Saved once per gesture, not per drag frame (each apply() rewrites the whole prefs file) + val persistBrightness: () -> Unit = { + if (brightnessPercentage >= 0f) sharedPreferences.edit().putFloat("pref_brightness", brightnessPercentage).apply() + } + LaunchedEffect(Unit) { val savedBright = sharedPreferences.getFloat("pref_brightness", -1f) if (savedBright > 0f) { @@ -539,6 +546,7 @@ Box( showVolumeHud = false }, onDragEnd = { + persistBrightness() hudJob?.cancel() hudJob = coroutineScope.launch { delay(800) @@ -546,6 +554,7 @@ Box( } }, onDragCancel = { + persistBrightness() hudJob?.cancel() hudJob = coroutineScope.launch { delay(800) @@ -567,7 +576,6 @@ Box( lp.screenBrightness = nextBright activity.window.attributes = lp brightnessPercentage = nextBright - sharedPreferences.edit().putFloat("pref_brightness", nextBright).apply() } hudJob?.cancel() @@ -665,8 +673,8 @@ Box( AnimatedVisibility( visible = showOverlay, modifier = Modifier.align(Alignment.BottomCenter), - enter = fadeIn(tween(200)), - exit = fadeOut(tween(200)) + enter = fadeIn(tween(150)), + exit = fadeOut(tween(150)) ) { Box( modifier = Modifier @@ -770,10 +778,20 @@ Box( } } - // Center Replay / Play action button when video ends or when overlay is open + // Center Replay / Play action button when video ends or when overlay is open. + // While playing it hides after 1.5s, well before the rest of the overlay (4s): + // it covers the video, the progress bar and actions don't. val isEnded = exoPlayer.playbackState == Player.STATE_ENDED + var centerButtonVisible by remember { mutableStateOf(showOverlay) } + LaunchedEffect(showOverlay, isPlaying) { + centerButtonVisible = showOverlay + if (showOverlay && isPlaying) { + delay(1500) + centerButtonVisible = false + } + } AnimatedVisibility( - visible = (showOverlay && showPlayPauseTransient == null) || (isEnded && showPlayPauseTransient == null), + visible = (centerButtonVisible && showPlayPauseTransient == null) || (isEnded && showPlayPauseTransient == null), modifier = Modifier.align(Alignment.Center), enter = fadeIn(tween(150)) + scaleIn(tween(150), initialScale = 0.85f), exit = fadeOut(tween(150)) + scaleOut(tween(150), targetScale = 0.85f) @@ -923,8 +941,8 @@ Box( AnimatedVisibility( visible = showOverlay, modifier = Modifier.align(Alignment.BottomStart), - enter = fadeIn(tween(220)) + slideInVertically(tween(220), initialOffsetY = { it / 2 }), - exit = fadeOut(tween(180)) + slideOutVertically(tween(180), targetOffsetY = { it / 2 }) + enter = fadeIn(tween(160)) + slideInVertically(tween(160), initialOffsetY = { it / 4 }), + exit = fadeOut(tween(140)) + slideOutVertically(tween(140), targetOffsetY = { it / 4 }) ) { Column( modifier = Modifier @@ -1035,10 +1053,13 @@ Box( } Spacer(modifier = Modifier.height(10.dp)) - // Horizontal row of quick action buttons + // Horizontal row of quick action buttons: scrolls when the 8 buttons + // are wider than the screen (narrow phones, large font or display size) Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically ) { // Comments button diff --git a/app/src/main/java/com/example/reddittube/ui/main/components/ThumbnailImage.kt b/app/src/main/java/com/example/reddittube/ui/main/components/ThumbnailImage.kt index 085e9c0..43ddd72 100644 --- a/app/src/main/java/com/example/reddittube/ui/main/components/ThumbnailImage.kt +++ b/app/src/main/java/com/example/reddittube/ui/main/components/ThumbnailImage.kt @@ -122,7 +122,7 @@ fun ThumbnailImage(url: String, contentDescription: String?, modifier: Modifier Box(modifier = modifier) { AnimatedVisibility( visible = currentBitmap != null, - enter = androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(250)) + enter = androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(150)) ) { if (currentBitmap != null) { Box(modifier = Modifier.fillMaxSize()) { diff --git a/app/src/main/java/com/example/reddittube/util/AdaptiveCacheEngine.kt b/app/src/main/java/com/example/reddittube/util/AdaptiveCacheEngine.kt index 177860c..8756d03 100644 --- a/app/src/main/java/com/example/reddittube/util/AdaptiveCacheEngine.kt +++ b/app/src/main/java/com/example/reddittube/util/AdaptiveCacheEngine.kt @@ -97,7 +97,7 @@ class AdaptiveCacheEngine( val target = dynamicCapacity val now = SystemClock.elapsedRealtime() while (store.size > target) { - val candidate = store.filter { (k, n) -> + val candidate = store.entries.asSequence().filter { (k, n) -> !isProtectedKey(k) || (now - n.lastAccessedMs > protectedTtlMs) }.minByOrNull { computeScore(it.value, now) } ?: break val removedNode = store.remove(candidate.key) diff --git a/app/src/main/java/com/example/reddittube/util/PerfTelemetryController.kt b/app/src/main/java/com/example/reddittube/util/PerfTelemetryController.kt index 3d7bcde..cf300ea 100644 --- a/app/src/main/java/com/example/reddittube/util/PerfTelemetryController.kt +++ b/app/src/main/java/com/example/reddittube/util/PerfTelemetryController.kt @@ -54,6 +54,8 @@ class PerfTelemetryController private constructor(context: Context) { fun recordStartupTime(durationMs: Long) { startupTimes.add(durationMs) + // Keep a rolling window: the list was unbounded and getStartupP95() sorts all of it + while (startupTimes.size > 200) startupTimes.removeAt(0) Log.i("PerfTelemetry", "Video startup latency: ${durationMs}ms (P95: ${getStartupP95()}ms)") } diff --git a/app/src/main/java/com/example/reddittube/utils/DownloadHelper.kt b/app/src/main/java/com/example/reddittube/utils/DownloadHelper.kt index 632336b..3982352 100644 --- a/app/src/main/java/com/example/reddittube/utils/DownloadHelper.kt +++ b/app/src/main/java/com/example/reddittube/utils/DownloadHelper.kt @@ -38,12 +38,15 @@ object DownloadHelper { onComplete: (Boolean, String?) -> Unit ) { withContext(Dispatchers.IO) { + var tempVideoFile: File? = null + var tempAudioFile: File? = null + var tempOutputFile: File? = null + var pendingUri: android.net.Uri? = null try { onProgress("Downloading video...") - val tempVideoFile = File(context.cacheDir, "temp_video_${System.currentTimeMillis()}.mp4") + tempVideoFile = File(context.cacheDir, "temp_video_${System.currentTimeMillis()}.mp4") downloadFile(context, fallbackUrl, tempVideoFile) - var tempAudioFile: File? = null if (dashUrl.isNotEmpty()) { onProgress("Checking audio...") try { @@ -91,28 +94,26 @@ object DownloadHelper { val uri = resolver.insert(collection, contentValues) if (uri != null) { - val tempOutputFile = File(context.cacheDir, "temp_output_${System.currentTimeMillis()}.mp4") - - muxVideoAndAudio(tempVideoFile, tempAudioFile, tempOutputFile) + pendingUri = uri + val outputFile = File(context.cacheDir, "temp_output_${System.currentTimeMillis()}.mp4") + tempOutputFile = outputFile + + muxVideoAndAudio(tempVideoFile, tempAudioFile, outputFile) resolver.openFileDescriptor(uri, "w")?.use { pfd -> - FileInputStream(tempOutputFile).use { input -> + FileInputStream(outputFile).use { input -> FileOutputStream(pfd.fileDescriptor).use { output -> input.copyTo(output) } } } - if (tempOutputFile.exists()) tempOutputFile.delete() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { contentValues.clear() contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0) resolver.update(uri, contentValues, null, null) } - - if (tempVideoFile.exists()) tempVideoFile.delete() - tempAudioFile?.let { if (it.exists()) it.delete() } + pendingUri = null withContext(Dispatchers.Main) { onComplete(true, displayName) @@ -122,9 +123,12 @@ object DownloadHelper { } } catch (e: Exception) { Log.e("DownloadHelper", "Download failed: ${e.message}", e) + pendingUri?.let { runCatching { context.contentResolver.delete(it, null, null) } } withContext(Dispatchers.Main) { onComplete(false, e.message) } + } finally { + listOfNotNull(tempVideoFile, tempAudioFile, tempOutputFile).forEach { if (it.exists()) it.delete() } } } } @@ -191,69 +195,49 @@ object DownloadHelper { } val videoExtractor = MediaExtractor() - videoExtractor.setDataSource(videoFile.absolutePath) - val audioExtractor = MediaExtractor() - audioExtractor.setDataSource(audioFile.absolutePath) - - val muxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) + var muxer: MediaMuxer? = null + try { + videoExtractor.setDataSource(videoFile.absolutePath) + audioExtractor.setDataSource(audioFile.absolutePath) - var videoTrackIndex = -1 - for (i in 0 until videoExtractor.trackCount) { - val format = videoExtractor.getTrackFormat(i) - val mime = format.getString(MediaFormat.KEY_MIME) ?: "" - if (mime.startsWith("video/")) { - videoExtractor.selectTrack(i) - videoTrackIndex = muxer.addTrack(format) - break + val videoFormatIndex = (0 until videoExtractor.trackCount).firstOrNull { + videoExtractor.getTrackFormat(it).getString(MediaFormat.KEY_MIME)?.startsWith("video/") == true } - } - - var audioTrackIndex = -1 - for (i in 0 until audioExtractor.trackCount) { - val format = audioExtractor.getTrackFormat(i) - val mime = format.getString(MediaFormat.KEY_MIME) ?: "" - if (mime.startsWith("audio/")) { - audioExtractor.selectTrack(i) - audioTrackIndex = muxer.addTrack(format) - break + val audioFormatIndex = (0 until audioExtractor.trackCount).firstOrNull { + audioExtractor.getTrackFormat(it).getString(MediaFormat.KEY_MIME)?.startsWith("audio/") == true } - } - - muxer.start() - - val videoBuffer = ByteBuffer.allocate(1024 * 1024) - val videoBufferInfo = MediaCodec.BufferInfo() - while (true) { - videoBufferInfo.offset = 0 - videoBufferInfo.size = videoExtractor.readSampleData(videoBuffer, 0) - if (videoBufferInfo.size < 0) break - videoBufferInfo.presentationTimeUs = videoExtractor.sampleTime - videoBufferInfo.flags = videoExtractor.sampleFlags - muxer.writeSampleData(videoTrackIndex, videoBuffer, videoBufferInfo) - videoExtractor.advance() - } - - if (audioTrackIndex != -1) { - val audioBuffer = ByteBuffer.allocate(1024 * 1024) - val audioBufferInfo = MediaCodec.BufferInfo() - while (true) { - audioBufferInfo.offset = 0 - audioBufferInfo.size = audioExtractor.readSampleData(audioBuffer, 0) - if (audioBufferInfo.size < 0) break - audioBufferInfo.presentationTimeUs = audioExtractor.sampleTime - audioBufferInfo.flags = audioExtractor.sampleFlags - muxer.writeSampleData(audioTrackIndex, audioBuffer, audioBufferInfo) - audioExtractor.advance() + if (videoFormatIndex == null || audioFormatIndex == null) { + Log.w("DownloadHelper", "Missing track (video=$videoFormatIndex, audio=$audioFormatIndex), saving video file as-is") + videoFile.copyTo(outputFile, overwrite = true) + return } - } - try { - muxer.stop() - } catch (e: Exception) { - Log.e("DownloadHelper", "Muxer stop failed", e) + val m = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) + muxer = m + videoExtractor.selectTrack(videoFormatIndex) + val videoTrackIndex = m.addTrack(videoExtractor.getTrackFormat(videoFormatIndex)) + audioExtractor.selectTrack(audioFormatIndex) + val audioTrackIndex = m.addTrack(audioExtractor.getTrackFormat(audioFormatIndex)) + m.start() + + val buffer = ByteBuffer.allocate(1024 * 1024) + val bufferInfo = MediaCodec.BufferInfo() + for ((extractor, trackIndex) in listOf(videoExtractor to videoTrackIndex, audioExtractor to audioTrackIndex)) { + while (true) { + bufferInfo.offset = 0 + bufferInfo.size = extractor.readSampleData(buffer, 0) + if (bufferInfo.size < 0) break + bufferInfo.presentationTimeUs = extractor.sampleTime + bufferInfo.flags = extractor.sampleFlags + m.writeSampleData(trackIndex, buffer, bufferInfo) + extractor.advance() + } + } + // A failed stop() means the output file is unusable: let it fail the download + m.stop() } finally { - muxer.release() + muxer?.release() videoExtractor.release() audioExtractor.release() } diff --git a/app/src/main/java/com/example/reddittube/utils/ExternalMediaResolver.kt b/app/src/main/java/com/example/reddittube/utils/ExternalMediaResolver.kt index 921780c..3b33adb 100644 --- a/app/src/main/java/com/example/reddittube/utils/ExternalMediaResolver.kt +++ b/app/src/main/java/com/example/reddittube/utils/ExternalMediaResolver.kt @@ -8,7 +8,6 @@ import kotlinx.coroutines.withContext import org.json.JSONObject import java.net.HttpURLConnection import java.net.URL -import java.util.concurrent.ConcurrentHashMap object ExternalMediaResolver { private const val TAG = "ExternalMediaResolver" @@ -19,7 +18,12 @@ object ExternalMediaResolver { private var cachedRedgifsToken: String? = null private var tokenExpiryTime: Long = 0L - private val resolvedCache = ConcurrentHashMap() + // Bounded LRU (up to 3 keys per video), synchronized because resolution runs on IO threads + private val resolvedCache: MutableMap = java.util.Collections.synchronizedMap( + object : LinkedHashMap(64, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?) = size > 600 + } + ) fun isRedgifsUrl(url: String): Boolean { return url.contains("redgifs.com", ignoreCase = true) || url.contains("gfycat.com", ignoreCase = true) diff --git a/app/src/test/java/com/example/reddittube/ui/main/MainScreenViewModelTest.kt b/app/src/test/java/com/example/reddittube/ui/main/MainScreenViewModelTest.kt index ab0dcd1..85f1b92 100644 --- a/app/src/test/java/com/example/reddittube/ui/main/MainScreenViewModelTest.kt +++ b/app/src/test/java/com/example/reddittube/ui/main/MainScreenViewModelTest.kt @@ -76,7 +76,7 @@ class MainScreenViewModelTest { @Test fun `initial state is Loading`() = runTest(testDispatcher) { val repo = FakeRepository() - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) assert(viewModel.exploreState.value is MainScreenUiState.Loading) assert(viewModel.subscribedState.value is MainScreenUiState.Loading) } @@ -87,7 +87,7 @@ class MainScreenViewModelTest { RedditPost("1", "Test Video", "test", "author", 100, "/r/test/1", "url", "url", "", "") ) val repo = FakeRepository(fetchResult = { flowOf(posts) }) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.refreshExplore() testDispatcher.scheduler.advanceUntilIdle() @@ -99,7 +99,7 @@ class MainScreenViewModelTest { @Test fun `refreshExplore emits Error when repository throws`() = runTest(testDispatcher) { val repo = FakeRepository(fetchResult = { flow { throw RedditError.NetworkError("Timeout") } }) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.refreshExplore() testDispatcher.scheduler.advanceUntilIdle() @@ -111,7 +111,7 @@ class MainScreenViewModelTest { @Test fun `refreshSubscribed with empty query shows error`() = runTest(testDispatcher) { val repo = FakeRepository() - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.refreshSubscribed("") testDispatcher.scheduler.advanceUntilIdle() @@ -129,7 +129,7 @@ class MainScreenViewModelTest { )) } ) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) val existing = RedditPost("existing_id", "Old Video", "test", "author", 100, "/r/test/1", "url", "url", "", "") viewModel.markAsWatched(existing) viewModel.refreshExplore() @@ -147,7 +147,7 @@ class MainScreenViewModelTest { fetchResult = { flowOf(emptyList()) }, afterMap = { mapOf("shorts" to null, "TikTokCringe" to null) } ) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.refreshExplore() testDispatcher.scheduler.advanceUntilIdle() @@ -158,7 +158,7 @@ class MainScreenViewModelTest { @Test fun `searchSubreddits emits empty list for short queries`() = runTest(testDispatcher) { val repo = FakeRepository() - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.searchSubreddits("a") assert(viewModel.searchResults.value.isEmpty()) assert(!viewModel.isSubredditSearching.value) @@ -169,7 +169,7 @@ class MainScreenViewModelTest { val repo = FakeRepository( searchResult = { flowOf(listOf("gaming", "games")) } ) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.searchSubreddits("gam", immediate = true) testDispatcher.scheduler.advanceUntilIdle() @@ -187,7 +187,7 @@ class MainScreenViewModelTest { RedditPost("unique_2", "Unique 2", "test", "author2", 50, "/r/test/2", "url", "url", "", "") ) val repo = FakeRepository(fetchResult = { flowOf(posts) }) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.refreshExplore() testDispatcher.scheduler.advanceUntilIdle() @@ -213,7 +213,7 @@ class MainScreenViewModelTest { fetchMoreResult = { flowOf(FetchMoreResult(morePosts, mapOf("test" to "t3_after"))) }, afterMap = { mapOf("test" to "t3_init") } ) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.refreshExplore() testDispatcher.scheduler.advanceUntilIdle() @@ -237,7 +237,7 @@ class MainScreenViewModelTest { flowOf(com.lean.reddittube.data.SearchVideosResult(listOf(searchPost), "cursor_1")) } ) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.searchVideos("cats", sort = "top&t=day", immediate = true) testDispatcher.scheduler.advanceUntilIdle() @@ -257,7 +257,7 @@ class MainScreenViewModelTest { flowOf(com.lean.reddittube.data.SearchVideosResult(listOf(searchPost), "cursor_sub")) } ) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.searchVideos("zelda", sort = "hot", immediate = true, subreddit = "gaming") testDispatcher.scheduler.advanceUntilIdle() @@ -275,7 +275,7 @@ class MainScreenViewModelTest { flowOf(com.lean.reddittube.data.SearchVideosResult(listOf(searchPost), "after_1")) } ) - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) viewModel.setSubredditSearchActive(true) assert(viewModel.isSubredditSearchActive.value) @@ -294,7 +294,7 @@ class MainScreenViewModelTest { @Test fun `markAsWatched orders newest first and bumps re-watched post`() = runTest(testDispatcher) { val repo = FakeRepository() - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) val post1 = RedditPost("p1", "First", "sub", "author", 10, "/r/sub/1", "url", "url", "", "") val post2 = RedditPost("p2", "Second", "sub", "author", 20, "/r/sub/2", "url", "url", "", "") @@ -322,7 +322,7 @@ class MainScreenViewModelTest { @Test fun `toggleLike orders newest first`() = runTest(testDispatcher) { val repo = FakeRepository() - val viewModel = MainScreenViewModel(repo) + val viewModel = MainScreenViewModel(repo, testDispatcher) val post1 = RedditPost("like_1", "First Liked", "sub", "author", 10, "/r/sub/1", "url", "url", "", "") val post2 = RedditPost("like_2", "Second Liked", "sub", "author", 20, "/r/sub/2", "url", "url", "", "")