class Repository( private val networkDataSource: NetworkDataSource, private val synchronizationDebounceMillis: Long = 2000L, coroutineContext: CoroutineContext = Dispatchers.Default ) : FeaturedPageDynamicCarouselRepository { private val dataChannel = ConflatedBroadcastChannel>>(Uninitialized) private val refreshChannel = ConflatedBroadcastChannel() init { GlobalScope.launch(coroutineContext) { var refreshFlow = refreshChannel.asFlow() if (synchronizationDebounceMillis > 0) { refreshFlow = refreshFlow.debounce(synchronizationDebounceMillis) } refreshFlow.collect { dataChannel.offer(Loading(dataChannel.value())) val networkResult = networkDataSource.getData() dataChannel.offer(networkResult.toAsync()) } } } override fun refresh() { refreshChannel.offer(Unit) } override fun observeData() = dataChannel.asFlow() override fun getData() = dataChannel.value }