Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
viewModelJob.cancel() но это подходит только если вы больше не планируете запускать на этом Job других корутин. Иначе, если планируете дальнейшее использование CoroutineScope, нужно использовать viewModelJob.cancelChildren()import kotlinx.coroutines.*
class CoroutinesCancelationClass {
private val job = Job()
private val scope = CoroutineScope(Dispatchers.IO + job)
fun doWork(tag: String) {
scope.launch{
println("start $tag")
delay(1000)
println("end $tag")
}
}
fun cancel(){
job.cancel()
}
fun cancelChildren() {
job.cancelChildren()
}
}
fun testCancelChildren() {
val testObj = CoroutinesCancelationClass()
testObj.doWork("testCancelChildren 1")
testObj.cancelChildren()
testObj.doWork("testCancelChildren 2")
}
fun testCancel() {
val testObj = CoroutinesCancelationClass()
testObj.doWork("testCancel 1")
testObj.cancel()
testObj.doWork("testCancel 2")
}
fun main(args: Array<String>) = runBlocking {
testCancel()
delay(2000)
testCancelChildren()
delay(2000)
}start testCancel 1
start testCancelChildren 1
start testCancelChildren 2
end testCancelChildren 2но это подходит только если вы больше не планируете запускать на этом Job других корутин.
@Override
protected void onDestroy() {
super.onDestroy();
if (mViewModelStore != null && !isChangingConfigurations()) {
mViewModelStore.clear();
}
mFragments.dispatchDestroy();
} private var viewModelJob = SupervisorJob()
private inline fun <P> doCoroutineWork(
crossinline doOnAsyncBlock: suspend CoroutineScope.() -> P,
coroutineScope: CoroutineScope,
context: CoroutineContext
) {
coroutineScope.launch {
withContext(context) {
try {
doOnAsyncBlock.invoke(this)
} catch (e: UnknownHostException) {
e.printStackTrace()
Log.d(TAG, "Server is unreachable")
} catch (e: SocketTimeoutException) {
e.printStackTrace()
Log.d(TAG, "No internet connection")
}
}
}
}class MyViewMode : BaseViewMode(), CoroutineScope by MainScope() {
fun onDestroy() {
cancel() // метод CoroutineScope
// or
coroutineContext[Job]?.cancelChildren()
}
fun showSomeData() = launch {
draw(data)
}
}
Опыт применения Coroutines и Retrofit2