我正在研究Google提供的蓝图样本 https://github.com/googlesamples/android-architecture/tree/todo-mvvm-live-kotlin 在数据源层中,他们使用两种不同的方式来处理暂停功能:
withContext<Unit>(ioDispatcher) {
....
}
等:
withContext(ioDispatcher) {
...
}
它们之间有什么区别?
答案 0 :(得分:1)
withContext
has a generic argument,它指定您传入的lambda的返回类型。如果lambda不返回任何内容,则最好显式使用Unit
返回类型,在这种情况下,如果您的lambda错误返回了某些内容,则会发出警告。
// No warnings, the result has Int type, which has been inferred automatically
val result = withContext(ioDispatcher) { 123 }
// "The expression is unused" warning, because the lambda should't return anything
val result = withContext<Unit>(ioDispatcher) { 123 }