👉 Основная логика лежит в
ViewModelImpl (можно посмотреть тут)👉
isCleared, Простой флаг указывающий на состояние viewModel. Много функций завязано на нем👉
closeables, keyToCloseables, addCloseable(). Все призвано для управления AutoCloseable ресурсами (Что за AutoCloseable?)👉
clear() Подчищает эти самые ресурсыКак думаете, что мы чаще всего добавляем в
addCloseable()? Правильно - viewModelScope, который в свою очередь является наследником AutoCloseable и CoroutineScope, которая останавливается по закрытию viewModel.
internal fun createViewModelScope(): CloseableCoroutineScope {
// dispatcher initialization
return CloseableCoroutineScope(coroutineContext = dispatcher + SupervisorJob())
}
internal class CloseableCoroutineScope(
override val coroutineContext: CoroutineContext,
) : AutoCloseable, CoroutineScope {
constructor(coroutineScope: CoroutineScope) : this(coroutineScope.coroutineContext)
override fun close() = coroutineContext.cancel()
}