handling co-routines with viewModel Scope

This commit is contained in:
Vitor Pamplona
2023-01-19 17:56:22 -05:00
parent fc88c2867d
commit 451137e8fa

View File

@@ -28,6 +28,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class NostrChannelFeedViewModel: FeedViewModel(NostrChannelDataSource) class NostrChannelFeedViewModel: FeedViewModel(NostrChannelDataSource)
class NostrChatroomListFeedViewModel: FeedViewModel(NostrChatroomListDataSource) class NostrChatroomListFeedViewModel: FeedViewModel(NostrChatroomListDataSource)
@@ -43,50 +44,39 @@ abstract class FeedViewModel(val dataSource: NostrDataSource<Note>): ViewModel()
val feedContent = _feedContent.asStateFlow() val feedContent = _feedContent.asStateFlow()
fun refresh() { fun refresh() {
val scope = CoroutineScope(Job() + Dispatchers.IO) viewModelScope.launch(Dispatchers.IO) {
scope.launch { val notes = dataSource.loadTop()
refreshSuspended()
}
}
private fun refreshSuspended() { val oldNotesState = feedContent.value
val notes = dataSource.loadTop() if (oldNotesState is FeedState.Loaded) {
if (notes != oldNotesState.feed) {
val oldNotesState = feedContent.value withContext(Dispatchers.Main) {
if (oldNotesState is FeedState.Loaded) { updateFeed(notes)
if (notes != oldNotesState.feed) { }
updateFeed(notes) }
} else {
withContext(Dispatchers.Main) {
updateFeed(notes)
}
} }
} else {
updateFeed(notes)
} }
} }
fun updateFeed(notes: List<Note>) { fun updateFeed(notes: List<Note>) {
val scope = CoroutineScope(Job() + Dispatchers.Main) if (notes.isEmpty()) {
scope.launch { _feedContent.update { FeedState.Empty }
if (notes.isEmpty()) { } else {
_feedContent.update { FeedState.Empty } _feedContent.update { FeedState.Loaded(notes) }
} else {
_feedContent.update { FeedState.Loaded(notes) }
}
} }
} }
fun refreshCurrentList() {
val state = feedContent.value
if (state is FeedState.Loaded) {
_feedContent.update { FeedState.Loaded(state.feed) }
}
}
val scope = CoroutineScope(Job() + Dispatchers.IO)
var handlerWaiting = false var handlerWaiting = false
@Synchronized @Synchronized
fun invalidateData() { fun invalidateData() {
if (handlerWaiting) return if (handlerWaiting) return
handlerWaiting = true handlerWaiting = true
val scope = CoroutineScope(Job() + Dispatchers.IO)
scope.launch { scope.launch {
delay(100) delay(100)
refresh() refresh()