implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
- viewmodel-ktx:
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1")
ViewModelScope虽然是协程,但属于
androidx.lifecycle
包中ViewModel的扩展属性
。
示例:
class MyViewModel :ViewModel() {
fun getData(){
viewModelScope.launch {
// do
}
}
}
使用非常简单,关键在于它是怎么保证不会内存泄露的?
来看viewModelScope
源码:
public val ViewModel.viewModelScope: CoroutineScope
get() {
val scope: CoroutineScope? = this.getTag(JOB_KEY)
if (scope != null) {
return scope
}
return setTagIfAbsent(
JOB_KEY,
CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
)
}
internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope {
override val coroutineContext: CoroutineCon