【发布时间】:2019-05-03 20:38:56
【问题描述】:
我有这样的视图模型
class StorageValidationViewModel: ViewModel(), CoroutineScope {
//Coroutines
private val _job = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + _job
override fun onCleared() {
super.onCleared()
coroutineContext.cancel()
}
......
}
我有一些方法可以通过Retrofit 发起网络调用来启动协程
fun getStorageLocations(){
launch {
var locations:List<StorageLocationData>? = null
try {
locations = _storageLocationRepository.getAllStorageLocations()
}catch (e:IOException){
e.printStackTrace()
}
storageLocationsLiveData.postValue(locations)
}
}
一切正常,但我感觉当 ViewModel 被清除时我没有正确取消协程,因为我实际上并没有在任何地方使用 coroutineContext 从而造成内存泄漏
我应该这样做吗
launch(coroutineContext){
//API call?
}
还是我做得很好?我只是想确保我所做的事情不会造成内存泄漏
【问题讨论】:
-
launch是CoroutineScope的扩展方法,你的ViewModel实现了它,所以看起来不错。另一个问题是,除非您的getAllStorageLocations是暂停方法,否则它可能不知道取消,并且无论如何都会继续执行。 -
@Pawel 是的
getAllStorageLocations是suspend fun因为改造 api 在拨打电话时使用await -
一切正常
标签: android kotlin android-architecture-components android-viewmodel kotlin-coroutines