I have one function inside that I am trigger an event at particular time.
fun startTimeWarning() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
if (!isActive) {
delay(2000)
// trigger event
}
}
}
}
Now I want to trigger new event in cancelTimeWarning
and make sure startTimeWarning
is not active. Is it possible to cancel in withContext
?
fun cancelTimeWarning() {
viewModelScope.launch {
// new event trigger
}
}
I checked in this answer but I don't think this will help me. Many thanks
CodePudding user response:
It's not that you want to use Job
or not. The viewModelScope.launch
will return a Coroutine Job, so that you can use this reference to cancel it manually in your case.
private var timeWarningJob: Job? = null
...
fun startTimeWarning() {
timeWarningJob = viewModelScope.launch {
withContext(Dispatchers.Default) {
if (!isActive) {
delay(2000)
// trigger event
}
}
}
}
fun cancelTimeWarning() {
timeWarningJob?.cancel() // Cancel your last job
viewModelScope.launch {
// new event trigger
}
}
Edited:
If your supervisor forbid you from using Job
, you can define your own context and cancel it later just like above.
private val timeWarningContext:CoroutineContext = Dispathers.Default
...
fun startTimeWarning() {
viewModelScope.launch {
withContext(timeWarningContext) {
if (!isActive) {
delay(2000)
// trigger event
}
}
}
}
fun cancelTimeWarning() {
timeWarningContext.cancel() // Cancel your last job
viewModelScope.launch {
// new event trigger
}
}