Bradleycorn
03/02/2021, 3:58 PMclass MyViewModel(): ViewModel() {
private var job: Job = viewModelScope.launch {
// Some long running async task, like polling a server or something
}
fun onSomeUIEvent() {
job.cancel()
}
}
Niklas Gürtler
03/02/2021, 4:01 PMBradleycorn
03/02/2021, 4:03 PMlaunch
in an init {}
and starting the job as null ... but then realized I can just set it straight away in the constructor.Niklas Gürtler
03/02/2021, 4:03 PMfmasa
03/02/2021, 6:43 PMuli
03/02/2021, 7:07 PMfmasa
03/02/2021, 7:10 PMBradleycorn
03/02/2021, 11:20 PMAdam Powell
03/03/2021, 1:14 AMBradleycorn
03/03/2021, 1:29 AMjob
in the ViewModel, more-so than launching from the constructor. I do see the risk in that. A better example for my question might be more like:
class MyViewModel(): ViewModel() {
private var job: Job? = null
fun onDownloadClick() {
job = viewModelScope.launch {
// Download some big file
}
}
fun onUserCanceled() {
job?.cancel()
}
}
Adam Powell
03/03/2021, 1:56 AMleandro
03/03/2021, 5:16 PM.init()
that would launch a coroutine?Adam Powell
03/03/2021, 8:01 PMsuspend fun run()
method to the object and call it from some other scope when it needs to be active, like lifecycle-bound scopes from a UI, etc.