From 2e2c85bae50d89963fd1e5b19be341e5a7a4c2a0 Mon Sep 17 00:00:00 2001 From: Gian <47775302+gpunto@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:24:56 +0100 Subject: [PATCH 1/3] Refetch a feed's loaded data when the connection is established again --- .../api/stream-feeds-android-client.api | 5 +- .../android/client/api/model/FeedsConfig.kt | 5 + .../android/client/internal/client/Create.kt | 17 +++ .../client/internal/client/FeedsClientImpl.kt | 3 + .../reconnect/ReconnectionRefetchHandler.kt | 102 +++++++++++++ .../android/client/internal/state/FeedImpl.kt | 80 +++++++++- .../client/internal/state/FeedStateImpl.kt | 29 ++++ .../android/client/internal/utils/Refetch.kt | 54 +++++++ .../internal/client/FeedsClientImplTest.kt | 1 + .../ReconnectionRefetchHandlerTest.kt | 137 ++++++++++++++++++ .../client/internal/state/FeedImplTest.kt | 126 ++++++++++++++++ .../client/internal/utils/RefetchPagesTest.kt | 80 ++++++++++ 12 files changed, 636 insertions(+), 3 deletions(-) create mode 100644 stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt create mode 100644 stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/utils/Refetch.kt create mode 100644 stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt create mode 100644 stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/utils/RefetchPagesTest.kt diff --git a/stream-feeds-android-client/api/stream-feeds-android-client.api b/stream-feeds-android-client/api/stream-feeds-android-client.api index a65f9ddb8..75685e749 100644 --- a/stream-feeds-android-client/api/stream-feeds-android-client.api +++ b/stream-feeds-android-client/api/stream-feeds-android-client.api @@ -891,11 +891,12 @@ public final class io/getstream/feeds/android/client/api/model/FeedVisibility$Vi public final class io/getstream/feeds/android/client/api/model/FeedsConfig { public fun ()V - public fun (Lio/getstream/feeds/android/client/api/file/Uploader;Lio/getstream/feeds/android/client/api/logging/LoggingConfig;Ljava/util/Map;)V - public synthetic fun (Lio/getstream/feeds/android/client/api/file/Uploader;Lio/getstream/feeds/android/client/api/logging/LoggingConfig;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lio/getstream/feeds/android/client/api/file/Uploader;Lio/getstream/feeds/android/client/api/logging/LoggingConfig;Ljava/util/Map;Z)V + public synthetic fun (Lio/getstream/feeds/android/client/api/file/Uploader;Lio/getstream/feeds/android/client/api/logging/LoggingConfig;Ljava/util/Map;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun getCustomHeaders ()Ljava/util/Map; public final fun getCustomUploader ()Lio/getstream/feeds/android/client/api/file/Uploader; public final fun getLoggingConfig ()Lio/getstream/feeds/android/client/api/logging/LoggingConfig; + public final fun getRefetchOnReconnect ()Z } public final class io/getstream/feeds/android/client/api/model/FeedsReactionData { diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/api/model/FeedsConfig.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/api/model/FeedsConfig.kt index 1b77a51d0..71ad597de 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/api/model/FeedsConfig.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/api/model/FeedsConfig.kt @@ -31,9 +31,14 @@ import io.getstream.feeds.android.client.api.logging.LoggingConfig * WebSocket. Headers controlled by the SDK or its HTTP stack cannot be overridden and are ignored * with a warning. Building the client rejects a name or value that is not valid HTTP, or two * names differing only in case, which HTTP treats as one header. + * @param refetchOnReconnect Whether state objects load their data again after the WebSocket + * reconnects, to pick up the changes made while it was disconnected. When `false`, feeds with + * [watch][io.getstream.feeds.android.client.api.state.query.FeedQuery.watch] set are still + * watched again, and calling `get()` or `getOrCreate()` updates the data. */ public class FeedsConfig( public val customUploader: FeedUploader? = null, public val loggingConfig: LoggingConfig = LoggingConfig(), public val customHeaders: Map = emptyMap(), + public val refetchOnReconnect: Boolean = true, ) diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt index dff273afa..b07941985 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt @@ -46,6 +46,7 @@ import io.getstream.feeds.android.client.api.file.FeedUploader import io.getstream.feeds.android.client.api.model.FeedsConfig import io.getstream.feeds.android.client.api.model.User import io.getstream.feeds.android.client.internal.client.reconnect.FeedWatchHandler +import io.getstream.feeds.android.client.internal.client.reconnect.ReconnectionRefetchHandler import io.getstream.feeds.android.client.internal.file.StreamFeedUploader import io.getstream.feeds.android.client.internal.http.FeedsSingleFlightApi import io.getstream.feeds.android.client.internal.http.createHttpConfig @@ -249,6 +250,21 @@ internal fun createFeedsClient( scope = clientScope, ) + val reconnectionRefetchHandler = + ReconnectionRefetchHandler( + connectionState = client.connectionState, + // Like the state event listeners, there is one per state object in use + refetchables = + StreamSubscriptionManager( + logProvider.taggedLogger("RefetchSubscriptions"), + maxStrongSubscriptions = Integer.MAX_VALUE, + maxWeakSubscriptions = Integer.MAX_VALUE, + ), + logger = logProvider.taggedLogger("RefetchHandler"), + scope = clientScope, + enabled = config.refetchOnReconnect, + ) + // Build client return FeedsClientImpl( apiKey = apiKey, @@ -276,6 +292,7 @@ internal fun createFeedsClient( stateEventsSubscriptionManager = stateEventsSubscriptionManager, stateEventEnricher = stateEventEnricher, feedWatchHandler = feedWatchHandler, + reconnectionRefetchHandler = reconnectionRefetchHandler, errorBus = errorBus, scope = clientScope, logger = logger, diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImpl.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImpl.kt index 762491047..bf19a5b23 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImpl.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImpl.kt @@ -73,6 +73,7 @@ import io.getstream.feeds.android.client.api.state.query.PollVotesQuery import io.getstream.feeds.android.client.api.state.query.PollsQuery import io.getstream.feeds.android.client.api.state.query.UsersQuery import io.getstream.feeds.android.client.internal.client.reconnect.FeedWatchHandler +import io.getstream.feeds.android.client.internal.client.reconnect.ReconnectionRefetchHandler import io.getstream.feeds.android.client.internal.repository.ActivitiesRepository import io.getstream.feeds.android.client.internal.repository.BookmarksRepository import io.getstream.feeds.android.client.internal.repository.CollectionsRepository @@ -150,6 +151,7 @@ internal class FeedsClientImpl( override val uploader: FeedUploader, override val moderation: Moderation, private val feedWatchHandler: FeedWatchHandler, + private val reconnectionRefetchHandler: ReconnectionRefetchHandler, private val logger: StreamLogger, scope: CoroutineScope, errorBus: Flow, @@ -241,6 +243,7 @@ internal class FeedsClientImpl( feedOwnValuesRepository = feedOwnValuesRepository, subscriptionManager = stateEventsSubscriptionManager, feedWatchHandler = feedWatchHandler, + reconnectionRefetchHandler = reconnectionRefetchHandler, ) override fun feedList(query: FeedsQuery): FeedList = diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt new file mode 100644 index 000000000..0f9cfa97c --- /dev/null +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-feeds-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.feeds.android.client.internal.client.reconnect + +import io.getstream.android.core.api.log.StreamLogger +import io.getstream.android.core.api.model.connection.StreamConnectionState +import io.getstream.android.core.api.subscribe.StreamSubscriptionManager +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.filterIsInstance +import kotlinx.coroutines.launch + +/** A state object that can load its data again, replacing what it has loaded. */ +internal fun interface Refetchable { + /** + * Loads the data again and replaces the loaded data with it. Does nothing if no data is loaded. + * Throws if a request fails. + */ + suspend fun refetch() +} + +/** + * Refetches the loaded data of the registered state objects when the connection is established + * again. + * + * Events sent while the connection is down are never delivered, so any loaded state can be out of + * date after a reconnection. + * + * @property connectionState A [Flow] of the connection state. + * @property refetchables The registered state objects. They are held weakly. + * @property logger The logger for refetch failures. + * @property scope The [CoroutineScope] in which to refetch. + * @param enabled Whether to refetch on reconnection. + */ +internal class ReconnectionRefetchHandler( + private val connectionState: Flow, + private val refetchables: StreamSubscriptionManager, + private val logger: StreamLogger, + private val scope: CoroutineScope, + enabled: Boolean, +) { + init { + if (enabled) { + scope.launch { refetchOnReconnection() } + } + } + + /** Registers [refetchable] for a refetch on every reconnection, for as long as it is in use. */ + fun register(refetchable: Refetchable) { + refetchables.subscribe(refetchable).onFailure { + logger.e(it) { "[register] Failed to register for a refetch on reconnection" } + } + } + + private suspend fun refetchOnReconnection() { + var connectionId: String? = null + var refetchJob: Job? = null + connectionState.filterIsInstance().collect { connected -> + // Every connection has its own id, so the first one is not a reconnection + val reconnected = connectionId != null && connectionId != connected.connectionId + connectionId = connected.connectionId + if (reconnected) { + // A newer reconnection cancels a refetch that is still running, so older data is + // not applied last + refetchJob?.cancel() + refetchJob = scope.launch { refetchAll() } + } + } + } + + private fun CoroutineScope.refetchAll() { + val targets = buildList { refetchables.forEach(::add) } + logger.d { "[refetchAll] Refetching ${targets.size} state objects after reconnection" } + targets.forEach { target -> launch { refetch(target) } } + } + + private suspend fun refetch(target: Refetchable) { + try { + target.refetch() + } catch (e: CancellationException) { + throw e + } catch (@Suppress("TooGenericExceptionCaught") e: Exception) { + logger.e(e) { "[refetch] Refetching data after reconnection failed" } + } + } +} diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt index eaedced0d..222243fa7 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt @@ -21,6 +21,7 @@ import io.getstream.android.core.api.filter.equal import io.getstream.android.core.api.subscribe.StreamSubscriptionManager import io.getstream.feeds.android.client.api.file.FeedUploadPayload import io.getstream.feeds.android.client.api.model.ActivityData +import io.getstream.feeds.android.client.api.model.AggregatedActivityData import io.getstream.feeds.android.client.api.model.BookmarkData import io.getstream.feeds.android.client.api.model.CommentData import io.getstream.feeds.android.client.api.model.FeedAddActivityRequest @@ -40,6 +41,9 @@ import io.getstream.feeds.android.client.api.state.query.FollowsFilterField import io.getstream.feeds.android.client.api.state.query.FollowsQuery import io.getstream.feeds.android.client.api.state.query.MembersQuery import io.getstream.feeds.android.client.internal.client.reconnect.FeedWatchHandler +import io.getstream.feeds.android.client.internal.client.reconnect.ReconnectionRefetchHandler +import io.getstream.feeds.android.client.internal.client.reconnect.Refetchable +import io.getstream.feeds.android.client.internal.model.PaginationResult import io.getstream.feeds.android.client.internal.repository.ActivitiesRepository import io.getstream.feeds.android.client.internal.repository.BookmarksRepository import io.getstream.feeds.android.client.internal.repository.CommentsRepository @@ -56,6 +60,7 @@ import io.getstream.feeds.android.client.internal.state.query.toRequest import io.getstream.feeds.android.client.internal.subscribe.StateUpdateEventListener import io.getstream.feeds.android.client.internal.subscribe.onEvent import io.getstream.feeds.android.client.internal.utils.flatMap +import io.getstream.feeds.android.client.internal.utils.refetchPages import io.getstream.feeds.android.network.models.AcceptFollowRequest import io.getstream.feeds.android.network.models.AddActivityRequest import io.getstream.feeds.android.network.models.AddBookmarkRequest @@ -73,6 +78,8 @@ import io.getstream.feeds.android.network.models.UpdateCommentRequest import io.getstream.feeds.android.network.models.UpdateFeedMembersRequest import io.getstream.feeds.android.network.models.UpdateFeedRequest import io.getstream.feeds.android.network.models.UpdateFollowRequest +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive /** * A feed represents a collection of activities and provides methods to interact with them. @@ -113,7 +120,8 @@ internal class FeedImpl( private val feedOwnValuesRepository: FeedOwnValuesRepository, private val subscriptionManager: StreamSubscriptionManager, private val feedWatchHandler: FeedWatchHandler, -) : Feed { + reconnectionRefetchHandler: ReconnectionRefetchHandler, +) : Feed, Refetchable { private val memberList: MemberListImpl = MemberListImpl( @@ -149,6 +157,7 @@ internal class FeedImpl( init { subscriptionManager.subscribe(eventHandler) + reconnectionRefetchHandler.register(this) } private val group: String @@ -176,6 +185,75 @@ internal class FeedImpl( .map { it.feed } } + override suspend fun refetch() { + if (_state.feed.value == null) { + // Nothing is loaded + return + } + refetchActivities() + if (_state.followRequestsPagination != null) { + refetchFollowRequests() + } + } + + private suspend fun refetchActivities() { + val loadedCount = _state.activities.value.size + _state.aggregatedActivities.value.size + val result = + refetchPages(loadedCount, FeedItem::id) { next -> + val info = feedsRepository.getOrCreateFeed(refetchQuery(next)).getOrThrow() + if (next == null) { + // Only the first page has the rest of the feed data + currentCoroutineContext().ensureActive() + _state.onRefetchFeed(info) + feedOwnValuesRepository.cache(info.feed) + } + val items = + info.activities.map(FeedItem::Single) + + info.aggregatedActivities.map(FeedItem::Group) + PaginationResult(items, info.pagination) + } + _state.onRefetchActivities( + activities = result.models.mapNotNull { (it as? FeedItem.Single)?.activity }, + aggregatedActivities = result.models.mapNotNull { (it as? FeedItem.Group)?.group }, + pagination = result.pagination, + ) + } + + /** The refetch starts at the top of the feed, also after loading around an activity. */ + private fun refetchQuery(next: String?): FeedQuery = + if (next == null) { + // Members are not refetched: they are managed by the member list + query.copy(activityIdAround = null, memberLimit = 0) + } else { + activitiesPageQuery(limit = null).copy(activityNext = next) + } + + private suspend fun refetchFollowRequests() { + val result = + refetchPages(_state.followRequests.value.size, FollowData::id) { next -> + feedsRepository + .queryFollows(followRequestsQuery.copy(next = next).toRequest()) + .getOrThrow() + } + _state.onQueryFollowRequests(result, replace = true) + } + + /** An entry of the feed: an activity, or a group of them in an aggregated feed. */ + private sealed interface FeedItem { + val id: Any + + data class Single(val activity: ActivityData) : FeedItem { + override val id: Any + get() = activity.id + } + + data class Group(val group: AggregatedActivityData) : FeedItem { + override val id: Any + // Kept apart from activity ids + get() = Group::class to group.group + } + } + override suspend fun stopWatching(): Result { feedWatchHandler.onStopWatching(query.fid) return feedsRepository.stopWatching(groupId = group, feedId = id) diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedStateImpl.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedStateImpl.kt index fc75517da..9e1e397a0 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedStateImpl.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedStateImpl.kt @@ -193,6 +193,22 @@ internal class FeedStateImpl( _aggregatedActivities.update { aggregatedActivities } } + override fun onRefetchFeed(result: GetOrCreateInfo) { + _feed.update { result.feed } + _followers.update { result.followers } + _following.update { result.following } + _pinnedActivities.update { result.pinnedActivities } + _notificationStatus.update { result.notificationStatus } + } + + override fun onRefetchActivities( + activities: List, + aggregatedActivities: List, + pagination: PaginationData, + ) { + onQueryActivitiesAround(activities, aggregatedActivities, pagination) + } + override fun onActivityAdded(activity: ActivityData, action: InsertionAction) { when (action) { InsertionAction.AddToStart -> { @@ -621,6 +637,19 @@ internal interface FeedStateUpdates { pagination: PaginationData, ) + /** + * Handles the feed data loaded again after a reconnection. The activities are replaced once all + * their pages are loaded, and the members are left to the member list. + */ + fun onRefetchFeed(result: GetOrCreateInfo) + + /** Handles the activities loaded again after a reconnection, replacing the loaded ones. */ + fun onRefetchActivities( + activities: List, + aggregatedActivities: List, + pagination: PaginationData, + ) + /** Handles updates to the feed state when activity is added. */ fun onActivityAdded(activity: ActivityData, action: InsertionAction) diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/utils/Refetch.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/utils/Refetch.kt new file mode 100644 index 000000000..c922581e0 --- /dev/null +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/utils/Refetch.kt @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-feeds-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.feeds.android.client.internal.utils + +import io.getstream.feeds.android.client.api.model.PaginationData +import io.getstream.feeds.android.client.internal.model.PaginationResult +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive + +/** + * Loads pages from the start until they cover [loadedCount] items, so that loaded data can be + * replaced with a fresh copy of the same size. At least the first page is loaded. + * + * @param loadedCount The number of items that are loaded now. + * @param idSelector Returns the identifier of an item. + * @param fetchPage Loads the page for the given next page token, or the first page for `null`. + * @return The loaded items in page order, with the pagination data of the last page. + */ +internal suspend fun refetchPages( + loadedCount: Int, + idSelector: (T) -> Any, + fetchPage: suspend (next: String?) -> PaginationResult, +): PaginationResult { + val models = LinkedHashMap() + var pagination = PaginationData.EMPTY + do { + val page = fetchPage(pagination.next) + currentCoroutineContext().ensureActive() + // A page that repeats loaded items means the tokens are not moving forward + val addsNewModels = page.models.any { idSelector(it) !in models } + page.models.forEach { model -> + // Items can move to a later page while refetching + val id = idSelector(model) + models.remove(id) + models[id] = model + } + pagination = page.pagination + } while (addsNewModels && models.size < loadedCount && pagination.next != null) + return PaginationResult(models.values.toList(), pagination) +} diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImplTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImplTest.kt index 311003943..0d2decb3d 100644 --- a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImplTest.kt +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/FeedsClientImplTest.kt @@ -142,6 +142,7 @@ internal class FeedsClientImplTest { uploader = uploader, moderation = moderation, feedWatchHandler = feedWatchHandler, + reconnectionRefetchHandler = mockk(relaxed = true), logger = logger, scope = scope, errorBus = errorBus, diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt new file mode 100644 index 000000000..cc51c9d7b --- /dev/null +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-feeds-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.feeds.android.client.internal.client.reconnect + +import io.getstream.android.core.api.model.connection.StreamConnectionState +import io.getstream.feeds.android.client.internal.test.TestSubscriptionManager +import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +internal class ReconnectionRefetchHandlerTest { + private val connectionState = MutableSharedFlow() + private val scope = TestScope(UnconfinedTestDispatcher()) + + @Test + fun `on first connection, then do not refetch`() = runTest { + val refetchable = CountingRefetchable() + createHandler().register(refetchable) + + connectionState.emit(connected("connection-1")) + + assertEquals(0, refetchable.count) + } + + @Test + fun `on reconnection, then refetch every registered object`() = runTest { + val first = CountingRefetchable() + val second = CountingRefetchable() + val handler = createHandler() + handler.register(first) + handler.register(second) + + connectionState.emit(connected("connection-1")) + connectionState.emit(StreamConnectionState.Disconnected()) + connectionState.emit(connected("connection-2")) + + assertEquals(1, first.count) + assertEquals(1, second.count) + } + + @Test + fun `on the same connection emitted again, then do not refetch`() = runTest { + val refetchable = CountingRefetchable() + createHandler().register(refetchable) + + connectionState.emit(connected("connection-1")) + connectionState.emit(connected("connection-1")) + + assertEquals(0, refetchable.count) + } + + @Test + fun `on reconnection when one refetch fails, then still refetch the others`() = runTest { + val refetchable = CountingRefetchable() + val handler = createHandler() + handler.register { error("failed") } + handler.register(refetchable) + + connectionState.emit(connected("connection-1")) + connectionState.emit(connected("connection-2")) + connectionState.emit(connected("connection-3")) + + assertEquals(2, refetchable.count) + } + + @Test + fun `on reconnection while a refetch is running, then cancel it`() = runTest { + val gate = CompletableDeferred() + var started = 0 + var finished = 0 + createHandler().register { + started++ + gate.await() + finished++ + } + + connectionState.emit(connected("connection-1")) + connectionState.emit(connected("connection-2")) + connectionState.emit(connected("connection-3")) + gate.complete(Unit) + + assertEquals(2, started) + assertEquals(1, finished) + } + + @Test + fun `on reconnection when disabled, then do not refetch`() = runTest { + val refetchable = CountingRefetchable() + createHandler(enabled = false).register(refetchable) + + connectionState.emit(connected("connection-1")) + connectionState.emit(connected("connection-2")) + + assertEquals(0, refetchable.count) + } + + private fun createHandler(enabled: Boolean = true) = + ReconnectionRefetchHandler( + connectionState = connectionState, + refetchables = TestSubscriptionManager(), + logger = mockk(relaxed = true), + scope = scope, + enabled = enabled, + ) + + private fun connected(connectionId: String) = + StreamConnectionState.Connected(mockk(), connectionId) + + private class CountingRefetchable : Refetchable { + var count = 0 + + override suspend fun refetch() { + count++ + } + } +} diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt index c8c30174c..fee40ab26 100644 --- a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt @@ -31,6 +31,7 @@ import io.getstream.feeds.android.client.api.model.request.ActivityAddCommentReq import io.getstream.feeds.android.client.api.state.query.ActivitiesFilterField import io.getstream.feeds.android.client.api.state.query.FeedQuery import io.getstream.feeds.android.client.internal.client.reconnect.FeedWatchHandler +import io.getstream.feeds.android.client.internal.client.reconnect.ReconnectionRefetchHandler import io.getstream.feeds.android.client.internal.model.PaginationResult import io.getstream.feeds.android.client.internal.repository.ActivitiesRepository import io.getstream.feeds.android.client.internal.repository.BookmarksRepository @@ -48,6 +49,7 @@ import io.getstream.feeds.android.client.internal.state.event.StateUpdateEvent.C import io.getstream.feeds.android.client.internal.state.event.handler.defaultOnNewActivity import io.getstream.feeds.android.client.internal.subscribe.StateUpdateEventListener import io.getstream.feeds.android.client.internal.test.TestData.activityData +import io.getstream.feeds.android.client.internal.test.TestData.aggregatedActivityData import io.getstream.feeds.android.client.internal.test.TestData.bookmarkData import io.getstream.feeds.android.client.internal.test.TestData.commentData import io.getstream.feeds.android.client.internal.test.TestData.feedData @@ -96,6 +98,7 @@ internal class FeedImplTest { private val pollsRepository: PollsRepository = mockk(relaxed = true) private val feedOwnValuesRepository: FeedOwnValuesRepository = mockk(relaxed = true) private val feedWatchHandler: FeedWatchHandler = mockk(relaxed = true) + private val reconnectionRefetchHandler: ReconnectionRefetchHandler = mockk(relaxed = true) private val stateEventListener: StateUpdateEventListener = mockk(relaxed = true) private val fid = FeedId("group:id") @@ -1110,6 +1113,128 @@ internal class FeedImplTest { verify { stateEventListener.onEvent(ActivityAdded(FidScope.unknown, activity)) } } + @Test + fun `on refetch with nothing loaded, then do nothing`() = runTest { + val feed = createFeed() + + feed.refetch() + + coVerify(exactly = 0) { feedsRepository.getOrCreateFeed(any()) } + } + + @Test + fun `on refetch, then load pages until they cover the loaded activities`() = runTest { + val query = + FeedQuery( + fid = fid, + activityLimit = 2, + memberLimit = 5, + activityIdAround = "activity-1", + ) + val feed = createFeed(query) + val member = feedMemberData() + setupInitialState( + feed, + // More than a page of the query's limit, as after loading more + activities = (1..3).map { activityData("activity-$it") }, + members = listOf(member), + ) + val firstPage = listOf(activityData("activity-0"), activityData("activity-1")) + val secondPage = listOf(activityData("activity-2")) + val refreshedFeed = feedData(name = "Refreshed") + // The first page starts at the top of the feed and leaves the members out + val firstQuery = query.copy(activityIdAround = null, memberLimit = 0) + val secondQuery = + FeedQuery( + fid = fid, + activityLimit = 2, + activityNext = "cursor", + followerLimit = 0, + followingLimit = 0, + memberLimit = 0, + ) + coEvery { feedsRepository.getOrCreateFeed(firstQuery) } returns + Result.success(getOrCreateInfo(refreshedFeed, activities = firstPage)) + coEvery { feedsRepository.getOrCreateFeed(secondQuery) } returns + Result.success( + getOrCreateInfo(feedData(), activities = secondPage) + .copy(pagination = PaginationData(next = "next-cursor")) + ) + + feed.refetch() + + assertEquals(firstPage + secondPage, feed.state.activities.value) + assertEquals(PaginationData(next = "next-cursor"), feed.state.activitiesPagination) + assertEquals(refreshedFeed, feed.state.feed.value) + assertEquals(listOf(member), feed.state.members.value) + } + + @Test + fun `on refetch of an aggregated feed, then replace the aggregated activities`() = runTest { + val feed = createFeed() + val loaded = aggregatedActivityData(group = "group-1") + coEvery { feedsRepository.getOrCreateFeed(any()) } returns + Result.success( + getOrCreateInfo(feedData()).copy(aggregatedActivities = listOf(loaded, loaded)) + ) + feed.getOrCreate() + val firstPage = listOf(aggregatedActivityData(group = "group-2")) + val secondPage = listOf(aggregatedActivityData(group = "group-1")) + coEvery { feedsRepository.getOrCreateFeed(any()) } returnsMany + listOf( + Result.success(getOrCreateInfo(feedData()).copy(aggregatedActivities = firstPage)), + Result.success( + getOrCreateInfo(feedData()) + .copy(aggregatedActivities = secondPage, pagination = PaginationData()) + ), + ) + + feed.refetch() + + assertEquals(firstPage + secondPage, feed.state.aggregatedActivities.value) + assertEquals(PaginationData(), feed.state.activitiesPagination) + } + + @Test + fun `on refetch with follow requests loaded, then refetch them`() = runTest { + val feed = createFeed() + setupInitialState(feed) + coEvery { feedsRepository.queryFollows(any()) } returns + Result.success(PaginationResult(listOf(pendingRequest("user:1")), PaginationData())) + feed.queryFollowRequests() + val refreshed = listOf(pendingRequest("user:2")) + coEvery { feedsRepository.queryFollows(any()) } returns + Result.success(PaginationResult(refreshed, PaginationData())) + + feed.refetch() + + assertEquals(refreshed, feed.state.followRequests.value) + } + + @Test + fun `on refetch without follow requests loaded, then do not query them`() = runTest { + val feed = createFeed() + setupInitialState(feed) + + feed.refetch() + + coVerify(exactly = 0) { feedsRepository.queryFollows(any()) } + } + + @Test + fun `on refetch when a page fails, then throw and keep the loaded activities`() = runTest { + val feed = createFeed() + val loaded = listOf(activityData("activity-1")) + setupInitialState(feed, activities = loaded) + val error = IllegalStateException("failed") + coEvery { feedsRepository.getOrCreateFeed(any()) } returns Result.failure(error) + + val result = runCatching { feed.refetch() } + + assertEquals(error, result.exceptionOrNull()) + assertEquals(loaded, feed.state.activities.value) + } + private fun createFeed(query: FeedQuery = FeedQuery(fid)) = FeedImpl( query = query, @@ -1123,6 +1248,7 @@ internal class FeedImplTest { feedOwnValuesRepository = feedOwnValuesRepository, subscriptionManager = TestSubscriptionManager(stateEventListener), feedWatchHandler = feedWatchHandler, + reconnectionRefetchHandler = reconnectionRefetchHandler, ) private fun pendingRequest(source: String, createdAt: Long = 1000) = diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/utils/RefetchPagesTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/utils/RefetchPagesTest.kt new file mode 100644 index 000000000..51495462a --- /dev/null +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/utils/RefetchPagesTest.kt @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-feeds-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.feeds.android.client.internal.utils + +import io.getstream.feeds.android.client.api.model.PaginationData +import io.getstream.feeds.android.client.internal.model.PaginationResult +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +internal class RefetchPagesTest { + private val requested = mutableListOf() + + @Test + fun `on nothing loaded, then load the first page only`() = runTest { + val result = refetch(loadedCount = 0, pages("a", "b"), pages("c")) + + assertEquals(PaginationResult(listOf("a", "b"), PaginationData(next = "1")), result) + assertEquals(listOf(null), requested) + } + + @Test + fun `on several pages loaded, then load pages until they cover the loaded count`() = runTest { + val result = refetch(loadedCount = 3, pages("a", "b"), pages("c", "d"), pages("e")) + + assertEquals( + PaginationResult(listOf("a", "b", "c", "d"), PaginationData(next = "2")), + result, + ) + assertEquals(listOf(null, "1"), requested) + } + + @Test + fun `on fewer items than loaded, then stop at the last page`() = runTest { + val result = refetch(loadedCount = 10, pages("a", "b"), pages("c")) + + assertEquals(PaginationResult(listOf("a", "b", "c"), PaginationData()), result) + assertEquals(listOf(null, "1"), requested) + } + + @Test + fun `on an item repeated on a later page, then keep its later position`() = runTest { + val result = refetch(loadedCount = 4, pages("a", "b"), pages("a", "c"), pages("d")) + + assertEquals(PaginationResult(listOf("b", "a", "c", "d"), PaginationData()), result) + } + + @Test + fun `on a page with no new items, then stop`() = runTest { + val result = refetch(loadedCount = 10, pages("a", "b"), pages("b", "a"), pages("c")) + + assertEquals(PaginationResult(listOf("b", "a"), PaginationData(next = "2")), result) + assertEquals(listOf(null, "1"), requested) + } + + private fun pages(vararg items: String) = items.toList() + + /** Serves [pages] in order, with the index of the following page as the next page token. */ + private suspend fun refetch(loadedCount: Int, vararg pages: List) = + refetchPages(loadedCount, idSelector = { it }) { next -> + requested += next + val index = next?.toInt() ?: 0 + val following = (index + 1).takeIf { it < pages.size }?.toString() + PaginationResult(pages[index], PaginationData(next = following)) + } +} From 6809bd57f006c01a94c4611104b11833f57d6873 Mon Sep 17 00:00:00 2001 From: Gian <47775302+gpunto@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:08:51 +0100 Subject: [PATCH 2/3] Let the feed refetch watch the feed again instead of a second request --- .../android/client/internal/client/Create.kt | 19 +++---- .../client/reconnect/FeedWatchHandler.kt | 38 +++++++++---- .../reconnect/ReconnectionRefetchHandler.kt | 17 +++++- .../android/client/internal/state/FeedImpl.kt | 31 ++++++++--- .../client/reconnect/FeedWatchHandlerTest.kt | 53 +++++++++++++++++++ .../ReconnectionRefetchHandlerTest.kt | 21 +++++++- .../client/internal/state/FeedImplTest.kt | 47 ++++++++++++++++ 7 files changed, 198 insertions(+), 28 deletions(-) diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt index b07941985..62a0c0569 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/Create.kt @@ -241,15 +241,6 @@ internal fun createFeedsClient( val moderation = ModerationImpl(moderationRepository) val errorBus = MutableSharedFlow(extraBufferCapacity = 100) - val feedWatchHandler = - FeedWatchHandler( - connectionState = client.connectionState, - feedsRepository = feedsRepository, - retryProcessor = StreamRetryProcessor(logProvider.taggedLogger("WatchHandler")), - errorBus = errorBus, - scope = clientScope, - ) - val reconnectionRefetchHandler = ReconnectionRefetchHandler( connectionState = client.connectionState, @@ -265,6 +256,16 @@ internal fun createFeedsClient( enabled = config.refetchOnReconnect, ) + val feedWatchHandler = + FeedWatchHandler( + connectionState = client.connectionState, + feedsRepository = feedsRepository, + retryProcessor = StreamRetryProcessor(logProvider.taggedLogger("WatchHandler")), + errorBus = errorBus, + scope = clientScope, + rewatchedByRefetch = reconnectionRefetchHandler::rewatchedFeeds, + ) + // Build client return FeedsClientImpl( apiKey = apiKey, diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandler.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandler.kt index b8729816f..ba66b1612 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandler.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandler.kt @@ -37,12 +37,14 @@ import kotlinx.coroutines.launch * Handles re-watching feeds upon reconnection. * * Keeps track of feeds that are being watched and re-subscribes to them when the connection is - * re-established. + * re-established. On a reconnection it leaves out the feeds that a refetch watches again, so those + * are not requested twice. * * @property connectionState A [Flow] that emits events when the connection state changes to * [StreamConnectionState.Connected]. * @property feedsRepository The [FeedsRepository] used to rewatch feeds on connection. * @property scope The [CoroutineScope] in which to launch coroutines for re-watching feeds. + * @property rewatchedByRefetch The feeds that the refetch on a reconnection starts watching again. */ internal class FeedWatchHandler( private val connectionState: Flow, @@ -50,13 +52,20 @@ internal class FeedWatchHandler( private val retryProcessor: StreamRetryProcessor, private val errorBus: MutableSharedFlow, private val scope: CoroutineScope, + private val rewatchedByRefetch: () -> Set = ::emptySet, ) { private val watched = ConcurrentHashMap() init { scope.launch { - connectionState.filterIsInstance().collect { - rewatchAll() + var connectionId: String? = null + connectionState.filterIsInstance().collect { connected + -> + // The refetch only runs on a reconnection, which is told apart the same way as in + // ReconnectionRefetchHandler + val reconnected = connectionId != null && connectionId != connected.connectionId + connectionId = connected.connectionId + rewatchAll(skipped = if (reconnected) rewatchedByRefetch() else emptySet()) } } } @@ -69,17 +78,26 @@ internal class FeedWatchHandler( watched -= feedId } - private suspend fun rewatchAll() { - coroutineScope { watched.keys.map { id -> async { rewatch(id) } } } - } + fun isWatching(feedId: FeedId): Boolean = watched.containsKey(feedId) - private suspend fun rewatch(id: FeedId): Result = + /** + * Runs [fetch], a request that starts watching [id] again, with the retries and the error + * reporting of a rewatch. + */ + suspend fun rewatch(id: FeedId, fetch: suspend () -> GetOrCreateInfo): Result = retryProcessor - .retry(retryPolicy) { - feedsRepository.getOrCreateFeed(FeedQuery(id, watch = true)).getOrThrow() - } + .retry(retryPolicy) { fetch() } .onFailure { errorBus.emit(StreamFeedRewatchException(id)) } + private suspend fun rewatchAll(skipped: Set) { + coroutineScope { + watched.keys.filterNot(skipped::contains).map { id -> async { rewatch(id) } } + } + } + + private suspend fun rewatch(id: FeedId): Result = + rewatch(id) { feedsRepository.getOrCreateFeed(FeedQuery(id, watch = true)).getOrThrow() } + companion object { private val retryPolicy = StreamRetryPolicy.exponential(maxRetries = 3) } diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt index 0f9cfa97c..d8277abd0 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandler.kt @@ -19,6 +19,7 @@ package io.getstream.feeds.android.client.internal.client.reconnect import io.getstream.android.core.api.log.StreamLogger import io.getstream.android.core.api.model.connection.StreamConnectionState import io.getstream.android.core.api.subscribe.StreamSubscriptionManager +import io.getstream.feeds.android.client.api.model.FeedId import kotlin.coroutines.cancellation.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -28,6 +29,13 @@ import kotlinx.coroutines.launch /** A state object that can load its data again, replacing what it has loaded. */ internal fun interface Refetchable { + /** + * The feed that [refetch] starts watching again, if any. Such a feed needs no separate request + * to watch it again after a reconnection. + */ + val rewatchedFeed: FeedId? + get() = null + /** * Loads the data again and replaces the loaded data with it. Does nothing if no data is loaded. * Throws if a request fails. @@ -53,7 +61,7 @@ internal class ReconnectionRefetchHandler( private val refetchables: StreamSubscriptionManager, private val logger: StreamLogger, private val scope: CoroutineScope, - enabled: Boolean, + private val enabled: Boolean, ) { init { if (enabled) { @@ -68,6 +76,13 @@ internal class ReconnectionRefetchHandler( } } + /** The feeds that the refetch on the next reconnection starts watching again. */ + fun rewatchedFeeds(): Set = buildSet { + if (enabled) { + refetchables.forEach { refetchable -> refetchable.rewatchedFeed?.let(::add) } + } + } + private suspend fun refetchOnReconnection() { var connectionId: String? = null var refetchJob: Job? = null diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt index 222243fa7..9964dcb3a 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt @@ -185,6 +185,9 @@ internal class FeedImpl( .map { it.feed } } + override val rewatchedFeed: FeedId? + get() = fid.takeIf { query.watch && _state.feed.value != null } + override suspend fun refetch() { if (_state.feed.value == null) { // Nothing is loaded @@ -200,7 +203,13 @@ internal class FeedImpl( val loadedCount = _state.activities.value.size + _state.aggregatedActivities.value.size val result = refetchPages(loadedCount, FeedItem::id) { next -> - val info = feedsRepository.getOrCreateFeed(refetchQuery(next)).getOrThrow() + val info = + if (next == null) { + refetchFirstPage() + } else { + val page = activitiesPageQuery(limit = null).copy(activityNext = next) + feedsRepository.getOrCreateFeed(page).getOrThrow() + } if (next == null) { // Only the first page has the rest of the feed data currentCoroutineContext().ensureActive() @@ -219,14 +228,22 @@ internal class FeedImpl( ) } - /** The refetch starts at the top of the feed, also after loading around an activity. */ - private fun refetchQuery(next: String?): FeedQuery = - if (next == null) { - // Members are not refetched: they are managed by the member list - query.copy(activityIdAround = null, memberLimit = 0) + /** + * The refetch starts at the top of the feed, also after loading around an activity. For a + * watched feed this request is also what starts watching it again after a reconnection. + */ + private suspend fun refetchFirstPage(): GetOrCreateInfo { + val watching = query.watch && feedWatchHandler.isWatching(fid) + // Members are not refetched: they are managed by the member list + val firstPage = query.copy(activityIdAround = null, memberLimit = 0, watch = watching) + return if (watching) { + feedWatchHandler + .rewatch(fid) { feedsRepository.getOrCreateFeed(firstPage).getOrThrow() } + .getOrThrow() } else { - activitiesPageQuery(limit = null).copy(activityNext = next) + feedsRepository.getOrCreateFeed(firstPage).getOrThrow() } + } private suspend fun refetchFollowRequests() { val result = diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandlerTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandlerTest.kt index f9fbbb311..753a8fe20 100644 --- a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandlerTest.kt +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/FeedWatchHandlerTest.kt @@ -26,6 +26,7 @@ import io.getstream.android.core.result.runSafely import io.getstream.feeds.android.client.api.model.FeedId import io.getstream.feeds.android.client.api.state.query.FeedQuery import io.getstream.feeds.android.client.internal.repository.FeedsRepository +import io.getstream.feeds.android.client.internal.repository.GetOrCreateInfo import io.mockk.called import io.mockk.coEvery import io.mockk.coVerify @@ -47,6 +48,8 @@ internal class FeedWatchHandlerTest { private val errorBus = MutableSharedFlow() private val scope = TestScope(UnconfinedTestDispatcher()) + private var rewatchedByRefetch = emptySet() + private val handler = FeedWatchHandler( connectionState = connectionEvents, @@ -54,6 +57,7 @@ internal class FeedWatchHandlerTest { retryProcessor = retryProcessor, errorBus = errorBus, scope = scope, + rewatchedByRefetch = { rewatchedByRefetch }, ) @Test @@ -96,6 +100,55 @@ internal class FeedWatchHandlerTest { } } + @Test + fun `on reconnection, skip the feeds that the refetch watches again`() = runTest { + coEvery { feedsRepository.getOrCreateFeed(any()) } returns Result.success(mockk()) + val id1 = FeedId("group", "id1") + val id2 = FeedId("group", "id2") + handler.onStartWatching(id1) + handler.onStartWatching(id2) + rewatchedByRefetch = setOf(id1) + + connectionEvents.emit(StreamConnectionState.Connected(mockk(), "connection-1")) + connectionEvents.emit(StreamConnectionState.Connected(mockk(), "connection-2")) + + // No refetch runs on the first connection, so both are watched there + coVerify(exactly = 1) { feedsRepository.getOrCreateFeed(FeedQuery(id1)) } + coVerify(exactly = 2) { feedsRepository.getOrCreateFeed(FeedQuery(id2)) } + } + + @Test + fun `on rewatch with a request, return its result`() = runTest { + val id = FeedId("group", "id1") + val info: GetOrCreateInfo = mockk() + + val result = handler.rewatch(id) { info } + + assertEquals(Result.success(info), result) + } + + @Test + fun `on rewatch with a request that fails, post error`() = runTest { + val id = FeedId("group", "id1") + + errorBus.test { + val result = handler.rewatch(id) { error("failed") } + + assertEquals(id, (awaitItem() as? StreamFeedRewatchException)?.id) + assertEquals(true, result.isFailure) + } + } + + @Test + fun `on isWatching, return whether the feed is being watched`() { + val id = FeedId("group", "id1") + handler.onStartWatching(id) + + assertEquals(true, handler.isWatching(id)) + handler.onStopWatching(id) + assertEquals(false, handler.isWatching(id)) + } + @Test fun `on non-connected event, do nothing`() = runTest { val id1 = FeedId("group", "id1") diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt index cc51c9d7b..3d06cdb80 100644 --- a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/ReconnectionRefetchHandlerTest.kt @@ -17,6 +17,7 @@ package io.getstream.feeds.android.client.internal.client.reconnect import io.getstream.android.core.api.model.connection.StreamConnectionState +import io.getstream.feeds.android.client.api.model.FeedId import io.getstream.feeds.android.client.internal.test.TestSubscriptionManager import io.mockk.mockk import kotlinx.coroutines.CompletableDeferred @@ -115,6 +116,24 @@ internal class ReconnectionRefetchHandlerTest { assertEquals(0, refetchable.count) } + @Test + fun `on rewatchedFeeds, then return the feeds that the registered objects watch again`() { + val feedId = FeedId("group", "id") + val handler = createHandler() + handler.register(CountingRefetchable()) + handler.register(CountingRefetchable(rewatchedFeed = feedId)) + + assertEquals(setOf(feedId), handler.rewatchedFeeds()) + } + + @Test + fun `on rewatchedFeeds when disabled, then return no feeds`() { + val handler = createHandler(enabled = false) + handler.register(CountingRefetchable(rewatchedFeed = FeedId("group", "id"))) + + assertEquals(emptySet(), handler.rewatchedFeeds()) + } + private fun createHandler(enabled: Boolean = true) = ReconnectionRefetchHandler( connectionState = connectionState, @@ -127,7 +146,7 @@ internal class ReconnectionRefetchHandlerTest { private fun connected(connectionId: String) = StreamConnectionState.Connected(mockk(), connectionId) - private class CountingRefetchable : Refetchable { + private class CountingRefetchable(override val rewatchedFeed: FeedId? = null) : Refetchable { var count = 0 override suspend fun refetch() { diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt index fee40ab26..5666f3c96 100644 --- a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/state/FeedImplTest.kt @@ -81,6 +81,7 @@ import io.getstream.feeds.android.network.models.UpdateFeedRequest import io.mockk.called import io.mockk.coEvery import io.mockk.coVerify +import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify @@ -102,6 +103,16 @@ internal class FeedImplTest { private val stateEventListener: StateUpdateEventListener = mockk(relaxed = true) private val fid = FeedId("group:id") + init { + // A watched feed, whose rewatch runs the request it is given + every { feedWatchHandler.isWatching(any()) } returns true + coEvery { feedWatchHandler.rewatch(any(), any()) } coAnswers + { + val fetch = secondArg GetOrCreateInfo>() + runCatching { fetch() } + } + } + @Test fun `on getOrCreate with watch enabled, then call feedWatchHandler`() = runTest { val feed = createFeed(FeedQuery(fid, watch = true)) @@ -1221,6 +1232,42 @@ internal class FeedImplTest { coVerify(exactly = 0) { feedsRepository.queryFollows(any()) } } + @Test + fun `on refetch of a watched feed, then fetch the first page as a rewatch`() = runTest { + val feed = createFeed(FeedQuery(fid, watch = true)) + setupInitialState(feed, activities = listOf(activityData("activity-1"))) + + feed.refetch() + + coVerify(exactly = 1) { feedWatchHandler.rewatch(fid, any()) } + coVerify { feedsRepository.getOrCreateFeed(FeedQuery(fid, watch = true, memberLimit = 0)) } + } + + @Test + fun `on refetch after the feed stopped being watched, then do not watch it again`() = runTest { + val feed = createFeed(FeedQuery(fid, watch = true)) + setupInitialState(feed, activities = listOf(activityData("activity-1"))) + every { feedWatchHandler.isWatching(fid) } returns false + + feed.refetch() + + coVerify(exactly = 0) { feedWatchHandler.rewatch(any(), any()) } + coVerify { feedsRepository.getOrCreateFeed(FeedQuery(fid, watch = false, memberLimit = 0)) } + } + + @Test + fun `on rewatchedFeed, then return the feed only when it is watched and loaded`() = runTest { + val notLoaded = createFeed(FeedQuery(fid, watch = true)) + val notWatched = createFeed(FeedQuery(fid, watch = false)) + val watched = createFeed(FeedQuery(fid, watch = true)) + setupInitialState(notWatched) + setupInitialState(watched) + + assertNull(notLoaded.rewatchedFeed) + assertNull(notWatched.rewatchedFeed) + assertEquals(fid, watched.rewatchedFeed) + } + @Test fun `on refetch when a page fails, then throw and keep the loaded activities`() = runTest { val feed = createFeed() From 9ad7659d65424633f62f99c3c97c6d39d44a68ba Mon Sep 17 00:00:00 2001 From: Gian <47775302+gpunto@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:27:09 +0100 Subject: [PATCH 3/3] Describe a paginated refetch with hooks, like the Swift SDK --- .../client/reconnect/PaginatedRefetchable.kt | 43 +++++++++++ .../android/client/internal/state/FeedImpl.kt | 59 +++++++-------- .../reconnect/PaginatedRefetchableTest.kt | 71 +++++++++++++++++++ 3 files changed, 144 insertions(+), 29 deletions(-) create mode 100644 stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchable.kt create mode 100644 stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchableTest.kt diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchable.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchable.kt new file mode 100644 index 000000000..79ede6e96 --- /dev/null +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchable.kt @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-feeds-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.feeds.android.client.internal.client.reconnect + +import io.getstream.feeds.android.client.internal.model.PaginationResult +import io.getstream.feeds.android.client.internal.utils.refetchPages + +/** + * A [Refetchable] that holds a paginated list. It only describes its list: [refetch] loads the + * pages again, from the first one, until they cover the loaded items. + */ +internal interface PaginatedRefetchable : Refetchable { + /** The number of loaded items, or null if nothing is loaded. */ + fun loadedCount(): Int? + + /** The id that tells [model] apart from the other items of the list. */ + fun idOf(model: T): Any + + /** Loads the page at [next], or the first page if it is null. Throws if the request fails. */ + suspend fun fetchPage(next: String?): PaginationResult + + /** Replaces the loaded items with the refetched ones. */ + fun onRefetched(result: PaginationResult) + + override suspend fun refetch() { + val loadedCount = loadedCount() ?: return + onRefetched(refetchPages(loadedCount, ::idOf) { next -> fetchPage(next) }) + } +} diff --git a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt index 9964dcb3a..9fc3713e5 100644 --- a/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt +++ b/stream-feeds-android-client/src/main/kotlin/io/getstream/feeds/android/client/internal/state/FeedImpl.kt @@ -41,8 +41,8 @@ import io.getstream.feeds.android.client.api.state.query.FollowsFilterField import io.getstream.feeds.android.client.api.state.query.FollowsQuery import io.getstream.feeds.android.client.api.state.query.MembersQuery import io.getstream.feeds.android.client.internal.client.reconnect.FeedWatchHandler +import io.getstream.feeds.android.client.internal.client.reconnect.PaginatedRefetchable import io.getstream.feeds.android.client.internal.client.reconnect.ReconnectionRefetchHandler -import io.getstream.feeds.android.client.internal.client.reconnect.Refetchable import io.getstream.feeds.android.client.internal.model.PaginationResult import io.getstream.feeds.android.client.internal.repository.ActivitiesRepository import io.getstream.feeds.android.client.internal.repository.BookmarksRepository @@ -121,7 +121,7 @@ internal class FeedImpl( private val subscriptionManager: StreamSubscriptionManager, private val feedWatchHandler: FeedWatchHandler, reconnectionRefetchHandler: ReconnectionRefetchHandler, -) : Feed, Refetchable { +) : Feed, PaginatedRefetchable { private val memberList: MemberListImpl = MemberListImpl( @@ -189,38 +189,39 @@ internal class FeedImpl( get() = fid.takeIf { query.watch && _state.feed.value != null } override suspend fun refetch() { - if (_state.feed.value == null) { - // Nothing is loaded - return - } - refetchActivities() + super.refetch() if (_state.followRequestsPagination != null) { refetchFollowRequests() } } - private suspend fun refetchActivities() { - val loadedCount = _state.activities.value.size + _state.aggregatedActivities.value.size - val result = - refetchPages(loadedCount, FeedItem::id) { next -> - val info = - if (next == null) { - refetchFirstPage() - } else { - val page = activitiesPageQuery(limit = null).copy(activityNext = next) - feedsRepository.getOrCreateFeed(page).getOrThrow() - } - if (next == null) { - // Only the first page has the rest of the feed data - currentCoroutineContext().ensureActive() - _state.onRefetchFeed(info) - feedOwnValuesRepository.cache(info.feed) - } - val items = - info.activities.map(FeedItem::Single) + - info.aggregatedActivities.map(FeedItem::Group) - PaginationResult(items, info.pagination) + override fun loadedCount(): Int? = + _state.feed.value?.let { + _state.activities.value.size + _state.aggregatedActivities.value.size + } + + override fun idOf(model: FeedItem): Any = model.id + + override suspend fun fetchPage(next: String?): PaginationResult { + val info = + if (next == null) { + refetchFirstPage() + } else { + val page = activitiesPageQuery(limit = null).copy(activityNext = next) + feedsRepository.getOrCreateFeed(page).getOrThrow() } + if (next == null) { + // Only the first page has the rest of the feed data + currentCoroutineContext().ensureActive() + _state.onRefetchFeed(info) + feedOwnValuesRepository.cache(info.feed) + } + val items = + info.activities.map(FeedItem::Single) + info.aggregatedActivities.map(FeedItem::Group) + return PaginationResult(items, info.pagination) + } + + override fun onRefetched(result: PaginationResult) { _state.onRefetchActivities( activities = result.models.mapNotNull { (it as? FeedItem.Single)?.activity }, aggregatedActivities = result.models.mapNotNull { (it as? FeedItem.Group)?.group }, @@ -256,7 +257,7 @@ internal class FeedImpl( } /** An entry of the feed: an activity, or a group of them in an aggregated feed. */ - private sealed interface FeedItem { + sealed interface FeedItem { val id: Any data class Single(val activity: ActivityData) : FeedItem { diff --git a/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchableTest.kt b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchableTest.kt new file mode 100644 index 000000000..9a98c9ae0 --- /dev/null +++ b/stream-feeds-android-client/src/test/kotlin/io/getstream/feeds/android/client/internal/client/reconnect/PaginatedRefetchableTest.kt @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2014-2026 Stream.io Inc. All rights reserved. + * + * Licensed under the Stream License; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://github.com/GetStream/stream-feeds-android/blob/main/LICENSE + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.getstream.feeds.android.client.internal.client.reconnect + +import io.getstream.feeds.android.client.api.model.PaginationData +import io.getstream.feeds.android.client.internal.model.PaginationResult +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +internal class PaginatedRefetchableTest { + + @Test + fun `on refetch with nothing loaded, then do not fetch`() = runTest { + val list = TestList(loadedCount = null) + + list.refetch() + + assertEquals(emptyList(), list.requestedPages) + assertNull(list.refetched) + } + + @Test + fun `on refetch, then replace the items with the pages that cover the loaded count`() = + runTest { + val list = TestList(loadedCount = 3) + + list.refetch() + + assertEquals(listOf(null, "page-2"), list.requestedPages) + val expected = PaginationResult(listOf("a", "b", "c", "d"), PaginationData(next = null)) + assertEquals(expected, list.refetched) + } + + private class TestList(private val loadedCount: Int?) : PaginatedRefetchable { + val requestedPages = mutableListOf() + var refetched: PaginationResult? = null + + override fun loadedCount(): Int? = loadedCount + + override fun idOf(model: String): Any = model + + override suspend fun fetchPage(next: String?): PaginationResult { + requestedPages += next + return if (next == null) { + PaginationResult(listOf("a", "b"), PaginationData(next = "page-2")) + } else { + PaginationResult(listOf("c", "d"), PaginationData(next = null)) + } + } + + override fun onRefetched(result: PaginationResult) { + refetched = result + } + } +}