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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 <init> ()V
public fun <init> (Lio/getstream/feeds/android/client/api/file/Uploader;Lio/getstream/feeds/android/client/api/logging/LoggingConfig;Ljava/util/Map;)V
public synthetic fun <init> (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 <init> (Lio/getstream/feeds/android/client/api/file/Uploader;Lio/getstream/feeds/android/client/api/logging/LoggingConfig;Ljava/util/Map;Z)V
public synthetic fun <init> (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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String> = emptyMap(),
public val refetchOnReconnect: Boolean = true,
)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -240,13 +241,29 @@ internal fun createFeedsClient(
val moderation = ModerationImpl(moderationRepository)
val errorBus = MutableSharedFlow<StreamClientException>(extraBufferCapacity = 100)

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,
)

val feedWatchHandler =
FeedWatchHandler(
connectionState = client.connectionState,
feedsRepository = feedsRepository,
retryProcessor = StreamRetryProcessor(logProvider.taggedLogger("WatchHandler")),
errorBus = errorBus,
scope = clientScope,
rewatchedByRefetch = reconnectionRefetchHandler::rewatchedFeeds,
)

// Build client
Expand Down Expand Up @@ -276,6 +293,7 @@ internal fun createFeedsClient(
stateEventsSubscriptionManager = stateEventsSubscriptionManager,
stateEventEnricher = stateEventEnricher,
feedWatchHandler = feedWatchHandler,
reconnectionRefetchHandler = reconnectionRefetchHandler,
errorBus = errorBus,
scope = clientScope,
logger = logger,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<StreamClientException>,
Expand Down Expand Up @@ -241,6 +243,7 @@ internal class FeedsClientImpl(
feedOwnValuesRepository = feedOwnValuesRepository,
subscriptionManager = stateEventsSubscriptionManager,
feedWatchHandler = feedWatchHandler,
reconnectionRefetchHandler = reconnectionRefetchHandler,
)

override fun feedList(query: FeedsQuery): FeedList =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,26 +37,35 @@ 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<StreamConnectionState>,
private val feedsRepository: FeedsRepository,
private val retryProcessor: StreamRetryProcessor,
private val errorBus: MutableSharedFlow<StreamClientException>,
private val scope: CoroutineScope,
private val rewatchedByRefetch: () -> Set<FeedId> = ::emptySet,
) {
private val watched = ConcurrentHashMap<FeedId, Unit>()

init {
scope.launch {
connectionState.filterIsInstance<StreamConnectionState.Connected>().collect {
rewatchAll()
var connectionId: String? = null
connectionState.filterIsInstance<StreamConnectionState.Connected>().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())
}
}
}
Expand All @@ -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<GetOrCreateInfo> =
/**
* 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<GetOrCreateInfo> =
retryProcessor
.retry(retryPolicy) {
feedsRepository.getOrCreateFeed(FeedQuery(id, watch = true)).getOrThrow()
}
.retry(retryPolicy) { fetch() }
.onFailure { errorBus.emit(StreamFeedRewatchException(id)) }

private suspend fun rewatchAll(skipped: Set<FeedId>) {
coroutineScope {
watched.keys.filterNot(skipped::contains).map { id -> async { rewatch(id) } }
}
}

private suspend fun rewatch(id: FeedId): Result<GetOrCreateInfo> =
rewatch(id) { feedsRepository.getOrCreateFeed(FeedQuery(id, watch = true)).getOrThrow() }

companion object {
private val retryPolicy = StreamRetryPolicy.exponential(maxRetries = 3)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<T> : 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<T>

/** Replaces the loaded items with the refetched ones. */
fun onRefetched(result: PaginationResult<T>)

override suspend fun refetch() {
val loadedCount = loadedCount() ?: return
onRefetched(refetchPages(loadedCount, ::idOf) { next -> fetchPage(next) })
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* 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 io.getstream.feeds.android.client.api.model.FeedId
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 {
/**
* 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.
*/
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<StreamConnectionState>,
private val refetchables: StreamSubscriptionManager<Refetchable>,
private val logger: StreamLogger,
private val scope: CoroutineScope,
private val 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" }
}
}

/** The feeds that the refetch on the next reconnection starts watching again. */
fun rewatchedFeeds(): Set<FeedId> = buildSet {
if (enabled) {
refetchables.forEach { refetchable -> refetchable.rewatchedFeed?.let(::add) }
}
}

private suspend fun refetchOnReconnection() {
var connectionId: String? = null
var refetchJob: Job? = null
connectionState.filterIsInstance<StreamConnectionState.Connected>().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" }
}
}
}
Loading
Loading