在 FavouriteListViewModel 中增加 EventBus 监听,以便在动态取消收藏时刷新列表。

This commit is contained in:
2025-08-05 15:47:30 +08:00
parent 7ea75a4755
commit 873001ce28

View File

@@ -15,10 +15,14 @@ import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentPagingSource
import com.aiosman.ravenow.entity.MomentRemoteDataSource
import com.aiosman.ravenow.entity.MomentServiceImpl
import com.aiosman.ravenow.event.MomentFavouriteChangeEvent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
object FavouriteListViewModel:ViewModel() {
private val momentService: MomentService = MomentServiceImpl()
@@ -26,12 +30,15 @@ object FavouriteListViewModel:ViewModel() {
MutableStateFlow<PagingData<MomentEntity>>(PagingData.empty())
val favouriteMomentsFlow = _favouriteMomentsFlow.asStateFlow()
var isLoading by mutableStateOf(false)
init {
EventBus.getDefault().register(this)
}
fun refreshPager(force:Boolean = false) {
viewModelScope.launch {
if (force) {
isLoading = true
}
isLoading = false
Pager(
config = PagingConfig(pageSize = 20, enablePlaceholders = false),
pagingSourceFactory = {
@@ -42,11 +49,22 @@ object FavouriteListViewModel:ViewModel() {
}
).flow.cachedIn(viewModelScope).collectLatest {
_favouriteMomentsFlow.value = it
isLoading = false
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onMomentFavouriteChangeEvent(event: MomentFavouriteChangeEvent) {
if (!event.isFavourite) {
// 当取消收藏时,刷新列表以移除该项目
refreshPager(force = true)
}
}
fun ResetModel() {
isLoading = false
EventBus.getDefault().unregister(this)
}
}