一个库(之前称为 KMM-ViewModel),允许您使用 AndroidX/Kotlin ViewModels 与 SwiftUI。
您可以在任何 KMP 项目中使用此库,但并非所有目标都支持 AndroidX 和/或 SwiftUI 互操作。
目标 | AndroidX | SwiftUI |
---|---|---|
Android | ✅ | - |
JVM | ✅ | - |
iOS | ✅ | ✅ |
macOS | ✅ | ✅ |
tvOS | - | ✅ |
watchOS | - | ✅ |
linuxX64 | ✅ | - |
linuxArm64 | - | - |
mingwX64 | - | - |
JS | - | - |
Wasm | - | - |
该库的最新版本使用 Kotlin 版本 1.9.24
。
还提供用于旧版本和/或预览版 Kotlin 的兼容性版本
版本 | 版本后缀 | Kotlin | 协程 | AndroidX 生命周期 |
---|---|---|---|---|
最新版本 | -kotlin-2.0.0-RC2 | 2.0.0-RC2 | 1.8.0 | 2.8.0-rc01 |
最新版本 | 无后缀 | 1.9.24 | 1.8.0 | 2.8.0-rc01 |
将库添加到您的共享 Kotlin 模块中,并选择 ExperimentalForeignApi
kotlin {
sourceSets {
all {
languageSettings.optIn("kotlinx.cinterop.ExperimentalForeignApi")
}
commonMain {
dependencies {
api("com.rickclephas.kmp:kmp-observableviewmodel-core:1.0.0-BETA-1")
}
}
}
}
然后创建您的 ViewModels
import com.rickclephas.kmp.observableviewmodel.ViewModel
import com.rickclephas.kmp.observableviewmodel.MutableStateFlow
import com.rickclephas.kmp.observableviewmodel.stateIn
open class TimeTravelViewModel: ViewModel() {
private val clockTime = Clock.time
/**
* A [StateFlow] that emits the actual time.
*/
val actualTime = clockTime.map { formatTime(it) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), "N/A")
private val _travelEffect = MutableStateFlow<TravelEffect?>(viewModelScope, null)
/**
* A [StateFlow] that emits the applied [TravelEffect].
*/
val travelEffect = _travelEffect.asStateFlow()
}
如您所注意到的,它与 AndroidX ViewModel 差不多。
显然,我们使用的是不同的 ViewModel
父类
- import androidx.lifecycle.ViewModel
+ import com.rickclephas.kmp.observableviewmodel.ViewModel
open class TimeTravelViewModel: ViewModel() {
除此之外,只有两个小小的不同。
第一个是不同的 stateIn
导入
- import kotlinx.coroutines.flow.stateIn
+ import com.rickclephas.kmp.observableviewmodel.stateIn
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), "N/A")
第二个是不同的 MutableStateFlow
构造器
- import kotlinx.coroutines.flow.MutableStateFlow
+ import com.rickclephas.kmp.observableviewmodel.MutableStateFlow
- private val _travelEffect = MutableStateFlow<TravelEffect?>(null)
+ private val _travelEffect = MutableStateFlow<TravelEffect?>(viewModelScope, null)
这些细微的差异将确保状态更改被传播到 SwiftUI。
注意
viewModelScope
是 CoroutineScope
的 包装器,可以通过 ViewModelScope.coroutineScope
属性访问。
我强烈推荐您使用来自 KMP-NativeCoroutines 的 @NativeCoroutinesState
注解,将您的 StateFlow
转换为 Swift 中的属性
@NativeCoroutinesState
val travelEffect = _travelEffect.asStateFlow()
有关更多信息及安装说明,请查阅 KMP-NativeCoroutines 的 README。
另一种选择
或者,您可以在 iOS/Apple 源集中自己创建扩展属性
val TimeTravelViewModel.travelEffectValue: TravelEffect?
get() = travelEffect.value
像使用任何其他的 AndroidX ViewModel 一样使用 ViewModel
class TimeTravelFragment: Fragment(R.layout.fragment_time_travel) {
private val viewModel: TimeTravelViewModel by viewModels()
}
将 Swift 包添加到您的 Package.swift
文件中
dependencies: [
.package(url: "https://github.com/rickclephas/KMP-ObservableViewModel.git", from: "1.0.0-BETA-1")
]
或者在 Xcode 中添加它,方法是转到 文件
> 添加包...
并提供 URL:https://github.com/rickclephas/KMP-ObservableViewModel.git
。
CocoaPods
如果您愿意,您也可以使用 CocoaPods 代替 SPM
pod 'KMPObservableViewModelSwiftUI', '1.0.0-BETA-1'
创建一个包含以下内容的 KMPObservableViewModel.swift
文件
import KMPObservableViewModelCore
import shared // This should be your shared KMP module
extension Kmp_observableviewmodel_coreViewModel: ViewModel { }
之后,您可以使用 view model 就像它是一个 ObservableObject
一样。
只需使用 view model 特定的属性包装和函数
ObservableObject |
ViewModel |
---|---|
@StateObject |
@StateViewModel |
@ObservedObject |
@ObservedViewModel |
@EnvironmentObject |
@EnvironmentViewModel |
environmentObject(_:) |
environmentViewModel(_:) |
例如,要使用 TimeTravelViewModel
作为 StateObject
import SwiftUI
import KMPObservableViewModelSwiftUI
import shared // This should be your shared KMP module
struct ContentView: View {
@StateViewModel var viewModel = TimeTravelViewModel()
}
在 Swift 中,您还可以对 ViewModel 进行子类化
import Combine
import shared // This should be your shared KMP module
class TimeTravelViewModel: shared.TimeTravelViewModel {
@Published var isResetDisabled: Bool = false
}
如果您的 ViewModel 公开了子 ViewModel,您可能需要一些额外的逻辑。
首先,请确保使用 NativeCoroutinesRefinedState
注解而不是 NativeCoroutinesState
注解。
class MyParentViewModel: ViewModel() {
@NativeCoroutinesRefinedState
val myChildViewModel: StateFlow<MyChildViewModel?> = MutableStateFlow(null)
}
之后,您应该使用 childViewModel(at:)
函数创建一个 Swift 扩展属性。
extension MyParentViewModel {
var myChildViewModel: MyChildViewModel? {
childViewModel(at: \.__myChildViewModel)
}
}
这将防止您的 Swift 视图模型过早被释放。
注意
对于包含视图模型的列表、集合和字典,有 childViewModels(at:)
。
当在 Swift 中继承 Kotlin ViewModel 时,您可能在使用 Combine 发布器通过 KMP-NativeCoroutines 监听 Flow 时遇到一些问题。
以下是一个此类问题的例子:您正在使用一个 Combine 发布器来通过 KMP-NativeCoroutines 监听 Flow。
import Combine
import KMPNativeCoroutinesCombine
import shared // This should be your shared KMP module
class TimeTravelViewModel: shared.TimeTravelViewModel {
private var cancellables = Set<AnyCancellable>()
override init() {
super.init()
createPublisher(for: currentTimeFlow)
.assertNoFailure()
.sink { time in print("It's \(time)") }
.store(in: &cancellables)
}
}
由于 currentTimeFlow
是一个 StateFlow,我们从未预期它会失败,这就是为什么我们使用了 assertNoFailure
。然而,在这种情况下,您会注意到发布器会因为 JobCancellationException
而失败。
这里的问题是,在 TimeTravelViewModel
被销毁之前,它已经被清除。这意味着 viewModelScope
被取消,并且调用了 onCleared
。这导致 Combine 发布器生命周期超过了底层的 StateFlow 集合的生命周期。
为了解决这个问题,您应该让您的 Swift 视图模型遵循 Cancellable
协议,并在 cancel
函数中执行必要的清理工作。
class TimeTravelViewModel: shared.TimeTravelViewModel, Cancellable {
func cancel() {
cancellables = []
}
}
KMP-ObservableViewModel 将确保在 ViewModel 被清理之前调用 cancel
函数。