Sync: should avoid having multiple sync loops

This commit is contained in:
ganfra
2023-07-10 13:08:55 +02:00
parent 3e69985fd6
commit 785c4a52f1
@@ -24,23 +24,30 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import org.matrix.rustcomponents.sdk.RoomListService import org.matrix.rustcomponents.sdk.RoomListService
import org.matrix.rustcomponents.sdk.RoomListServiceState import org.matrix.rustcomponents.sdk.RoomListServiceState
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean
class RustSyncService( class RustSyncService(
private val roomListService: RoomListService, private val roomListService: RoomListService,
sessionCoroutineScope: CoroutineScope sessionCoroutineScope: CoroutineScope
) : SyncService { ) : SyncService {
private val isSyncing = AtomicBoolean(false)
override fun startSync() = runCatching { override fun startSync() = runCatching {
if (!roomListService.isSyncing()) { if (isSyncing.compareAndSet(false, true)) {
Timber.v("Start sync")
roomListService.sync() roomListService.sync()
} }
} }
override fun stopSync() = runCatching { override fun stopSync() = runCatching {
if (roomListService.isSyncing()) { if (isSyncing.compareAndSet(true, false)) {
Timber.v("Stop sync")
roomListService.stopSync() roomListService.stopSync()
} }
} }
@@ -49,6 +56,12 @@ class RustSyncService(
roomListService roomListService
.stateFlow() .stateFlow()
.map(RoomListServiceState::toSyncState) .map(RoomListServiceState::toSyncState)
.onEach { state ->
Timber.v("Sync state=$state")
if (state == SyncState.InError || state == SyncState.Terminated) {
isSyncing.set(false)
}
}
.distinctUntilChanged() .distinctUntilChanged()
.stateIn(sessionCoroutineScope, SharingStarted.WhileSubscribed(), SyncState.Idle) .stateIn(sessionCoroutineScope, SharingStarted.Eagerly, SyncState.Idle)
} }