@@ -3,24 +3,36 @@ package com.example.fruitties.di.viewmodel
33import androidx.lifecycle.ViewModel
44import androidx.lifecycle.ViewModelProvider
55import androidx.lifecycle.ViewModelStore
6+ import androidx.lifecycle.ViewModelStoreOwner
67import androidx.lifecycle.viewmodel.CreationExtras
78import kotlinx.cinterop.BetaInteropApi
89import kotlinx.cinterop.ObjCClass
910import kotlinx.cinterop.getOriginalKotlinClass
1011import kotlin.reflect.KClass
1112
13+ /* *
14+ * This function allows retrieving any ViewModel from Swift Code with generics.
15+ * We only get [ObjCClass] type for the [modelClass], because the interop between Kotlin and Swift
16+ * code doesn't preserve the generic class, but we can retrieve the original KClass in Kotlin.
17+ */
1218@Suppress(" unused" ) // Android Studio is not aware of iOS usage.
1319@OptIn(BetaInteropApi ::class )
1420@Throws(IllegalStateException ::class )
1521fun ViewModelStore.getViewModel (
1622 modelClass : ObjCClass ,
1723 factory : ViewModelProvider .Factory ,
1824 key : String? ,
19- extras : CreationExtras ,
25+ extras : CreationExtras ? = null ,
2026): ViewModel {
2127 @Suppress(" UNCHECKED_CAST" )
2228 val vmClass = getOriginalKotlinClass(modelClass) as ? KClass <ViewModel >
2329 ? : error(" modelClass isn't a ViewModel type" )
24- val provider = ViewModelProvider .create(this , factory, extras)
30+ val provider = ViewModelProvider .create(this , factory, extras ? : CreationExtras . Empty )
2531 return key?.let { provider[key, vmClass] } ? : provider[vmClass]
2632}
33+
34+ /* *
35+ * The ViewModelStoreOwner isn't used anywhere in the project, therefore it's not visible for Swift by default.
36+ */
37+ @Suppress(" unused" )
38+ interface SwiftViewModelStoreOwner : ViewModelStoreOwner
0 commit comments