【发布时间】:2020-04-20 15:50:35
【问题描述】:
我有一个Foo 类,它包装了一个CountDownTimer:
class Foo() {
private val timer = object: CountDownTimer(2000, 1000) {
override fun onTick(millisUntilFinished: Long) {
// How MyViewModel could utilize this callback to get students in MyViewModel?
}
override fun onFinish() {
}
}
fun start() {
myTimer.start()
}
}
在我的 ViewModel 中:
class MyViewModel constructor(repo: MyRepo): ViewModel() {
fun getStudents(): LiveData<List<Student>> {
// How to introduce my Foo class here to get student list every 2 seconds
val studentList = liveData(Dispatchers.IO) {
val studentList = repo.getStudents()
emit(studentList)
}
return studentList
}
}
我想通过使用 Foo 类重构 MyViewModel 代码以每 2 秒获得一次学生,但我不知道该怎么做。有人可以指导我吗?
【问题讨论】:
-
您可以在视图模型中调用数据并通过 liveData 观察结果
-
@LiemVo 你能显示一些代码吗?
标签: android kotlin kotlin-coroutines kotlin-android-extensions