Android Room可观察的查询不会使用ViewModel第二次触发
在过去的10个小时中,寻找解决我的问题的解决方案,但我无法理解问题到底是什么,这使我发疯。
我有一个viewModel
其中init
我正在收集flow
像这样:
@HiltViewModel
class ExampleViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
init {
viewModelScope.launch {
taxCalendarUseCase
.observeCalendarBetweenDates(
startDate = uiState.selectedMonth.value.atDay(1),
endDate = uiState.selectedMonth.value.atEndOfMonth()
)
.distinctUntilChanged()
.collect { list ->
Timber.i("Collect is called with ${list.size} items")
uiState.taxCalendar.value = list
uiState.selectedCountry.value =
uiState.taxCalendar.value.map { it.countryCode }.distinct().firstOrNull()
?: ""
}
}
}
}
我的dao
看起来像这样:
@Dao
interface TaxCalendarDao {
@Query("SELECT * FROM tax_calendar WHERE date BETWEEN :start AND :end")
fun observeTaxCalendarListBetweenDates(start: String, end: String): Flow<List<TaxCalendarModel>>
}
基于我在收集
块中放置的日志,当我第一次打开composable
时(这是屏幕a),然后转到另一个composable
(屏幕b)我在数据库中添加一些数据的地方,当导航时,我期望再次调用collect
,但这不会发生。
EDIT1:我尝试更改调度程序,以添加oneach
,以删除distractillChanged
以制作mutableStateFlow
并在中收集存储库
Spent the last 10 hours searching for a solution to my problem, but I am not able to understand what exactly is the problem and it's driving me crazy.
I have a viewmodel
where on init
I am collecting a flow
like this:
@HiltViewModel
class ExampleViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
init {
viewModelScope.launch {
taxCalendarUseCase
.observeCalendarBetweenDates(
startDate = uiState.selectedMonth.value.atDay(1),
endDate = uiState.selectedMonth.value.atEndOfMonth()
)
.distinctUntilChanged()
.collect { list ->
Timber.i("Collect is called with ${list.size} items")
uiState.taxCalendar.value = list
uiState.selectedCountry.value =
uiState.taxCalendar.value.map { it.countryCode }.distinct().firstOrNull()
?: ""
}
}
}
}
And my DAO
looks like this:
@Dao
interface TaxCalendarDao {
@Query("SELECT * FROM tax_calendar WHERE date BETWEEN :start AND :end")
fun observeTaxCalendarListBetweenDates(start: String, end: String): Flow<List<TaxCalendarModel>>
}
Based on the log I've put in the collect
block, when I open my Composable
the first time it's called (This is screen A), then going to another Composable
(Screen B) where I add some data to the database, when navigating up I expect collect
being called again but this is not happening.
Edit1: I've tried to change the dispatcher, to add onEach
, to remove distinctUntillChanged
to make a mutableStateFlow
and collecting in the repository
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论