使用我的计时器在 ViewModel 中获取数据(在 kotlin 中)

Use my timer to get data in ViewModel (in kotlin)

我有一个 Foo class,其中包含一个 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 class 重构 MyViewModel 代码以每 2 秒获取一次学生,但我不确定该怎么做。有人可以指导我吗?

这是一个例子

class Foo(private val viewModel: MyViewModel) {
    private val timer = object: CountDownTimer(2000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            viewModel.loadStudents()
        }

        override fun onFinish() {
        }
    }

    fun start() {
        timer.start()
    }
}

Foo class 持有 ViewModel 的一个实例,并且可以调用方法 loadStudents 从您的存储库中获取数据

这是 ViewModel 的更新

class MyViewModel constructor(val repo: MyRepo): ViewModel() {

    private val _students = MutableLiveData<List<Student>>()
    val students: LiveData<List<Student>> // from your view (fragment or activity) observe this livedata
        get() = _students
    val foo = Foo(this)
    init {
        loadStudents()
    }

    fun loadStudents() {
        viewModelScope.launch(Dispatchers.IO){
            _students.postValue(repo.getStudents())
            foo.start()
        }
    }
}

repo.getStudents 的结果回复将发布在 liveData 中,您可以在视图中看到。