【问题标题】:Use my timer to get data in ViewModel (in kotlin)使用我的计时器在 ViewModel 中获取数据(在 kotlin 中)
【发布时间】: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


【解决方案1】:

这是一个例子

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 类拥有一个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。

【讨论】:

  • 我需要为 ViewModel 中的不同数据类型传入不同的时间间隔,该怎么做?
  • repo.getStudents完成后可以再次调用start
  • 在 start 之后调用 repo.getStudents 在间隔秒后调用,如何制作以便在调用 start 时立即获取学生,之后每隔间隔秒获取学生?
  • @Leem 现在 ViewModel 启动时会获取 student。
猜你喜欢
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多