commonMain.com.adeo.kviewmodel.odyssey.ViewModelStore.kt Maven / Gradle / Ivy
The newest version!
package com.adeo.kviewmodel.odyssey
import androidx.compose.runtime.DisallowComposableCalls
import com.adeo.kviewmodel.KViewModel
public object ViewModelStore {
@PublishedApi
internal val viewModelStore: ConcurrentHashMap = ConcurrentHashMap()
@PublishedApi
internal inline fun getOrPut(
screenKey: String,
factory: @DisallowComposableCalls () -> T
): T {
val key = "${screenKey}_${T::class.name}"
return viewModelStore.getOrPut(key, factory) as T
}
public fun remove(screenKey: String) {
val keys = viewModelStore.keys.filter { it.startsWith(screenKey) }
keys.forEach { key ->
viewModelStore[key]?.clear()
viewModelStore -= key
}
}
public fun removeAll() {
viewModelStore.values.forEach(KViewModel::clear)
viewModelStore.clear()
}
}