File tree Expand file tree Collapse file tree 3 files changed +40
-5
lines changed
shared/src/iosMain/kotlin/com/example/kmp/snippets Expand file tree Collapse file tree 3 files changed +40
-5
lines changed Original file line number Diff line number Diff line change 11import SwiftUI
2- import Shared
2+ import KmpKit
33
44struct ContentView : View {
55 @State private var showContent = false
@@ -16,7 +16,7 @@ struct ContentView: View {
1616 Image ( systemName: " swift " )
1717 . font ( . system( size: 200 ) )
1818 . foregroundColor ( . accentColor)
19- Text ( " SwiftUI: \( Greeting ( ) . greet ( ) ) " )
19+ Text ( " SwiftUI " )
2020 }
2121 . transition ( . move( edge: . top) . combined ( with: . opacity) )
2222 }
Original file line number Diff line number Diff line change 1+ import Foundation
2+ import KmpKit
3+
4+ // [START android_kmp_viewmodel_ios_viewmodel_storeowner]
5+ class IosViewModelStoreOwner : ObservableObject , ViewModelStoreOwner {
6+
7+ let viewModelStore = ViewModelStore ( )
8+
9+ /// This function allows retrieving the androidx ViewModel from the store.
10+ /// It uses the utilify function to pass the generic type T to shared code
11+ func viewModel< T: ViewModel > (
12+ key: String ? = nil ,
13+ factory: ViewModelProviderFactory ,
14+ extras: CreationExtras ? = nil
15+ ) -> T {
16+ do {
17+ return try viewModelStore. resolveViewModel (
18+ modelClass: T . self,
19+ factory: factory,
20+ key: key,
21+ extras: extras
22+ ) as! T
23+ } catch {
24+ fatalError ( " Failed to create ViewModel of type \( T . self) " )
25+ }
26+ }
27+
28+ /// This is called when this class is used as a `@StateObject`
29+ deinit {
30+ viewModelStore. clear ( )
31+ }
32+ }
33+ // [END android_kmp_viewmodel_ios_viewmodel_storeowner]
Original file line number Diff line number Diff line change 1- package com.example.kmp.snipets
1+ package com.example.kmp.snippets
22
33import androidx.lifecycle.ViewModel
44import androidx.lifecycle.ViewModelProvider
@@ -9,9 +9,10 @@ import kotlinx.cinterop.ObjCClass
99import kotlinx.cinterop.getOriginalKotlinClass
1010import kotlin.reflect.KClass
1111
12+ // [START android_kmp_viewmodel_resolve_viewmodel]
1213/* *
1314 * This function allows retrieving any ViewModel from Swift Code with generics. We only get
14- * [kotlinx.cinterop. ObjCClass] type for the [modelClass], because the interop between Kotlin and Swift code
15+ * [ObjCClass] type for the [modelClass], because the interop between Kotlin and Swift code
1516 * doesn't preserve the generic class, but we can retrieve the original KClass in Kotlin.
1617 */
1718@BetaInteropApi
@@ -28,4 +29,5 @@ fun ViewModelStore.resolveViewModel(
2829
2930 val provider = ViewModelProvider .Companion .create(this , factory, extras ? : CreationExtras .Empty )
3031 return key?.let { provider[key, vmClass] } ? : provider[vmClass]
31- }
32+ }
33+ // [END android_kmp_viewmodel_resolve_viewmodel]
You can’t perform that action at this time.
0 commit comments