使用Kotlin协程DSL打造MVVM架构App -- 基础知识

Coroutines, 是Kotlin的协程库。本质上,协程是轻量级的线程,除了更高效地实现并发, 使用它还可以桥接阻塞与非阻塞的世界。简单示例:编程

/**
* Wait one second then display a snackbar.
*/
fun onMainViewClicked() {
   // launch a coroutine in viewModelScope
   viewModelScope.launch {
       // suspend this coroutine for one second
       delay(1_000)
       // resume in the main dispatcher
       // _snackbar.value can be called directly from main thread
       _snackBar.value = "Hello, from coroutines!"
   }
}
复制代码

DSL(domain specific language),能够理解为具体编程语言之上, 针对特定领域问题的语言。你们感觉下这段单元测试代码:bash

val str = "kotlin"
str should startWith("kot")
str.length shouldBe 6
复制代码

有没以为“内容引发温馨”?架构

Data Binding 数据绑定,用于下降界面布局和业务逻辑代码的耦合性。具体一点讲,经过将数据单向或双向绑定到 layout 文件中,Data Binding 可以大量减小Activity或Fragment中的findViewById()/setText()/setImage()等步骤,有助于防止内存泄漏,并且能自动进行空检测以免空指针异常。并发

MVVM(Model/View/ViewModel) 架构范式相对于MVP, 更进一步下降了View层和Presenter之间的耦合,更完全地分离了各层的关注点。上图: dom

相关文章
相关标签/搜索