From e42298d32a2e351ceb9a0c4297ad957f5eebfaf2 Mon Sep 17 00:00:00 2001 From: Armand <4831c0@proton.me> Date: Wed, 16 Sep 2026 14:25:35 +0200 Subject: [PATCH] fix(cache): dedupe concurrent init and renewCache calls --- firka/lib/api/client/kreta_client.dart | 39 ++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/firka/lib/api/client/kreta_client.dart b/firka/lib/api/client/kreta_client.dart index 9ae8f68b..d8747461 100644 --- a/firka/lib/api/client/kreta_client.dart +++ b/firka/lib/api/client/kreta_client.dart @@ -177,12 +177,47 @@ class KretaClient { await getNoticeBoard(from: from); } - Future init() async { + Future? _initInFlight; + + /// Two `init()` calls close together (initialization.dart + a + /// reInit-triggered renewCache()) used to run fully concurrently and + /// interleave writes. Coalesce to one in-flight future. + Future init() { + final inFlight = _initInFlight; + if (inFlight != null) return inFlight; + final future = _initImpl(); + _initInFlight = future; + // whenComplete() would return an unawaited derived future, so an + // error here would get reported as unhandled even though real + // callers already catch it via the returned `future`. + future.then((_) => _initInFlight = null, onError: (_) => _initInFlight = null); + return future; + } + + Future _initImpl() async { await getStudent(); await getClassGroups(); } - Future renewCache({bool reInit = false}) async { + Future? _renewCacheInFlight; + + /// Multiple call sites trigger renewCache() close together on cold + /// start; without this a second call re-runs the whole sync concurrently + /// and can clobber the first's fresher writes. + Future renewCache({bool reInit = false}) { + final inFlight = _renewCacheInFlight; + if (inFlight != null) return inFlight; + final future = _renewCacheImpl(reInit: reInit); + _renewCacheInFlight = future; + // See init()'s comment on why this isn't future.whenComplete(...). + future.then( + (_) => _renewCacheInFlight = null, + onError: (_) => _renewCacheInFlight = null, + ); + return future; + } + + Future _renewCacheImpl({bool reInit = false}) async { _toastCubit.setActiveToast(.fetching); try { if (reInit) {