Skip to content

Commit e56036d

Browse files
committed
refactor: manage cache size observation lifecycle in ProfileViewModel
- Introduce `cacheSizeJob` to track the coroutine responsible for observing cache size changes. - Update `refreshCacheSize` to prevent spawning redundant observation jobs if one is already active. - Ensure the existing `cacheSizeJob` is cancelled and reset when clearing the cache to trigger a fresh update cycle.
1 parent d901a6c commit e56036d

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

  • feature/profile/presentation/src/commonMain/kotlin/zed/rainxch/profile/presentation

feature/profile/presentation/src/commonMain/kotlin/zed/rainxch/profile/presentation/ProfileViewModel.kt

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ class ProfileViewModel(
3838
private var userProfileJob: Job? = null
3939

4040
private var hasLoadedInitialData = false
41+
private var cacheSizeJob: Job? = null
4142

4243
private val _state = MutableStateFlow(ProfileState())
4344
val state =
@@ -72,13 +73,15 @@ class ProfileViewModel(
7273
val events = _events.receiveAsFlow()
7374

7475
private fun refreshCacheSize() {
75-
viewModelScope.launch {
76-
profileRepository.observeCacheSize().collect { sizeBytes ->
77-
_state.update {
78-
it.copy(cacheSize = formatCacheSize(sizeBytes))
76+
if (cacheSizeJob?.isActive == true) return
77+
cacheSizeJob =
78+
viewModelScope.launch {
79+
profileRepository.observeCacheSize().collect { sizeBytes ->
80+
_state.update {
81+
it.copy(cacheSize = formatCacheSize(sizeBytes))
82+
}
7983
}
8084
}
81-
}
8285
}
8386

8487
private fun formatCacheSize(bytes: Long): String {
@@ -312,6 +315,8 @@ class ProfileViewModel(
312315
runCatching {
313316
profileRepository.clearCache()
314317
}.onSuccess {
318+
cacheSizeJob?.cancel()
319+
cacheSizeJob = null
315320
refreshCacheSize()
316321
_events.send(ProfileEvent.OnCacheCleared)
317322
}.onFailure { error ->

0 commit comments

Comments
 (0)