@@ -18,11 +18,13 @@ import io.element.android.libraries.matrix.api.room.MatrixRoom
1818import io.element.android.libraries.matrix.api.timeline.Timeline
1919import io.element.android.libraries.matrix.api.timeline.TimelineProvider
2020import kotlinx.coroutines.CoroutineScope
21+ import kotlinx.coroutines.coroutineScope
2122import kotlinx.coroutines.flow.MutableStateFlow
2223import kotlinx.coroutines.flow.StateFlow
2324import kotlinx.coroutines.flow.combine
25+ import kotlinx.coroutines.flow.distinctUntilChanged
2426import kotlinx.coroutines.flow.launchIn
25- import kotlinx.coroutines.flow.onCompletion
27+ import kotlinx.coroutines.flow.map
2628import kotlinx.coroutines.flow.onEach
2729import javax.inject.Inject
2830
@@ -32,7 +34,8 @@ class PinnedEventsTimelineProvider @Inject constructor(
3234 private val networkMonitor : NetworkMonitor ,
3335 private val featureFlagService : FeatureFlagService ,
3436) : TimelineProvider {
35- private val _timelineStateFlow : MutableStateFlow <AsyncData <Timeline >> = MutableStateFlow (AsyncData .Uninitialized )
37+ private val _timelineStateFlow : MutableStateFlow <AsyncData <Timeline >> =
38+ MutableStateFlow (AsyncData .Uninitialized )
3639
3740 override fun activeTimelineFlow (): StateFlow <Timeline ?> {
3841 return _timelineStateFlow
@@ -44,25 +47,46 @@ class PinnedEventsTimelineProvider @Inject constructor(
4447 val timelineStateFlow = _timelineStateFlow
4548
4649 fun launchIn (scope : CoroutineScope ) {
50+ _timelineStateFlow .subscriptionCount
51+ .map { count -> count > 0 }
52+ .distinctUntilChanged()
53+ .onEach { isActive ->
54+ if (isActive) {
55+ onActive()
56+ } else {
57+ onInactive()
58+ }
59+ }
60+ .launchIn(scope)
61+ }
62+
63+ private suspend fun onActive () = coroutineScope {
4764 combine(
4865 featureFlagService.isFeatureEnabledFlow(FeatureFlags .PinnedEvents ),
4966 networkMonitor.connectivity
50- ) {
51- // do not use connectivity here as data can be loaded from cache, it's just to trigger retry if needed
52- isEnabled, _ ->
67+ ) { isEnabled, _ ->
68+ // do not use connectivity here as data can be loaded from cache, it's just to trigger retry if needed
5369 isEnabled
5470 }
5571 .onEach { isFeatureEnabled ->
5672 if (isFeatureEnabled) {
5773 loadTimelineIfNeeded()
5874 } else {
59- _timelineStateFlow .value = AsyncData . Uninitialized
75+ resetTimeline()
6076 }
6177 }
62- .onCompletion {
63- invokeOnTimeline { close() }
64- }
65- .launchIn(scope)
78+ .launchIn(this )
79+ }
80+
81+ private suspend fun onInactive () {
82+ resetTimeline()
83+ }
84+
85+ private suspend fun resetTimeline () {
86+ invokeOnTimeline {
87+ close()
88+ }
89+ _timelineStateFlow .emit(AsyncData .Uninitialized )
6690 }
6791
6892 suspend fun invokeOnTimeline (action : suspend Timeline .() -> Unit ) {
0 commit comments