java - 在 Android Kotlin 的观察者方法中进行网络调用以更新 UI
问题描述
我正在构建一个应用程序,用户可以在其中添加他们的日历可用性,并删除这些可用性。我在 Fragment 的 onViewCreated 中设置了一个观察者方法,每次用户单击我的日历日期时都会调用该方法。通过我当前的实现,代码第一次按预期工作,然后在后续调用中遇到了一些奇怪的错误(API 调用未通过/UI 未按预期更新)。我的代码如下:
init {
view.setOnClickListener {
dateTimeViewModel.haveOwnTimeslotsBeenUpdated.observe(
viewLifecycleOwner,
Observer { isOwnTimeslotUpdated ->
if (isOwnTimeslotUpdated) {
val startOfTimeframe =
LocalDate.now().yearMonth.minusMonths(10).atDay(1)
.atStartOfDay(timezone).toEpochSecond()
val endOfTimeframe =
LocalDate.now().yearMonth.plusMonths(10).atDay(1)
.atStartOfDay(
timezone
).toEpochSecond()
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
val response = dateTimeViewModel.getOwnTimeslots(
startOfTimeframe,
endOfTimeframe
)
val listOfTimeslots = handleResponse(response)
mapOfDatesAndTimeslots =
storeLocalDateAndTimeslotsInAMap(listOfTimeslots)
val dates = mapOfDatesAndTimeslots.keys
if(selectedDate in dates){
val listOfTimeslotsOnADate = mapOfDatesAndTimeslots[selectedDate]
val areTimeslotsWorthDisplaying = listOfTimeslotsOnADate!!.any{ timeslot ->
timeslot.timeslot_status == 0 || timeslot.timeslot_status == 1 || timeslot.timeslot_status == 2
}
if(areTimeslotsWorthDisplaying){
calendarDayDotView.visibility = View.VISIBLE
sortTimeslotsOnAParticularDate(listOfTimeslotsOnADate)
} else {
calendarDayDotView.visibility = View.INVISIBLE
clearRecyclerViews()
}
} else {
calendarDayDotView.visibility = View.INVISIBLE
clearRecyclerViews()
}
}
dateTimeViewModel.setHaveOwnTimeslotsBeenUpdatedToFalse()
}
}
)
}
}
第一次调用后,我显示点的 UI 没有按预期工作,尽管第一次工作正常,我的时间段排序也没有。我有一种感觉,这是因为这行代码被反复调用:viewLifecycleOwner.lifecycleScope.launchWhenStarted
但我可能是错的。我不确定从观察者方法中进行 API 调用然后将观察到的变量重置为 false 是否是最佳做法,因此请分享您的建议(如果有)。请帮助我,并提前谢谢你:D
解决方案
你的视图模型是什么样的?
一个红旗将在您的点击侦听器中设置观察者,但我不确定您是否正在考虑它,因此更多代码会很高兴查看
推荐阅读
- java - 从同一项目/服务连接到 2 个模式的正确方法是什么?
- sql - 用“;”分隔的每个值创建新列 SQL Server 子字符串
- java - (HackerRank Day 2: Operators) 构造函数的问题
- magento - 更改购物车中的产品名称,报价单,发票 Magento 2
- php - docker 中的 Composer 私有存储库
- r - 在 R 过滤器中,一个表的行基于与另一个表的匹配和日期小于另一个表
- json - 如何将 I18n 实现为 JPA 或 Hibernate 实体的 JSON 对象?
- bash - 自定义编写的 Nagios 插件总是返回不正确的值,但在命令行上工作
- sql - postgresql - 将间隔格式化为具有大量小时数的时间
- javascript - 如何检测浏览器的chrome