KMPObservableViewModelCoreObjC 1.0.0-BETA-4

KMPObservableViewModelCoreObjC 1.0.0-BETA-4

Rick Clephas 维护。



  • Rick Clephas

KMP-ObservableViewModel

一个库(以前称为 KMM-ViewModel),允许您在不同平台上使用 SwiftUI 与 Kotlin ViewModels。

兼容性

您可以在任何 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

将库添加到您的 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。

注意

viewModelScopeCoroutineScope 的包装,可以通过 ViewModelScope.coroutineScope 属性访问。

KMP-NativeCoroutines

我强烈建议您使用来自 KMP-NativeCoroutines@NativeCoroutinesState 注解,将您的 StateFlow 转换为 Swift 中的属性。

@NativeCoroutinesState
val travelEffect = _travelEffect.asStateFlow()

有关更多信息,请参阅 KMP-NativeCoroutines 的 README,以及安装说明。

替代方案

或者,您可以自己创建 iOS/Apple 源集的扩展属性

val TimeTravelViewModel.travelEffectValue: TravelEffect?
    get() = travelEffect.value

Android

像使用其他 AndroidX ViewModel 一样使用 ViewModel

class TimeTravelFragment: Fragment(R.layout.fragment_time_travel) {
    private val viewModel: TimeTravelViewModel by viewModels()
}

Swift

将 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 { }

之后,您可以几乎像使用 ObservableObject 一样使用您的 ViewModel。
只需要使用特定于 ViewModel 的属性包装和函数

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 中也可以对视图模型进行子类化

import Combine
import shared // This should be your shared KMP module

class TimeTravelViewModel: shared.TimeTravelViewModel {
    @Published var isResetDisabled: Bool = false
}

子视图模型

如果你的 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:)

可取消的 ViewModel

当你在 Swift 中对 Kotlin ViewModel 进行子类化时,可能会遇到一些清除方式的问题。

这种问题的例子是当你使用 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 函数。