在安卓Kotlin中的观察者方法中进行网络调用以更新UI



我正在构建一个应用程序,用户可以在其中添加日历可用性,并删除这些可用性。我在我的Fragment的onViewCreated中设置了一个observer方法,每当用户点击我的日历日期时就会调用它。通过我当前的实现,代码第一次按预期工作,然后我在随后的调用中遇到了一些奇怪的bug(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

您的视图模型是什么样子的?

一个危险信号是在你的点击监听器中设置观察者,但我不确定你是否在考虑它,因此更多的代码会很好地审查

最新更新