KMPObservableViewModelSwiftUI 1.0.0-BETA-4

KMPObservableViewModelSwiftUI 1.0.0-BETA-4

Rick Clephas 维护。



  • Rick Clephas

KMP-ObservableViewModel

一个库(以前被称为 KMM-ViewModel),允许您在 SwiftUI 中使用 AndroidX/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 Lifecycle
最新版 -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。

注意

viewModelScope 是对实际 CoroutineScope 的包装,可以通过 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 一样使用视图模型

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 来使用。
只需使用视图模型特定的属性包装器和函数即可

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
}

子视图模型

如果您暴露了子视图模型,需要一定的额外逻辑。

首先,确保使用 NativeCoroutinesRefinedState 注解而不是 NativeCoroutinesState 注解

class MyParentViewModel: ViewModel() {
    @NativeCoroutinesRefinedState
    val myChildViewModel: StateFlow<MyChildViewModel?> = MutableStateFlow(null)
}

然后,应该创建一个 Swift 扩展属性,并使用 childViewModel(at:) 函数

extension MyParentViewModel {
    var myChildViewModel: MyChildViewModel? {
        childViewModel(at: \.__myChildViewModel)
    }
}

这将防止 Swift 视图模型过早被释放。

注意

对于包含视图模型的列表、集合和字典,有 childViewModels(at:)

可取消的视图模型

当在 Swift 中继承 Kotlin 视图模型时,您可能会遇到一些关于视图模型清理方式的问题。

此类问题的一个例子是您正在使用 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 被 deinited 之前,它已经被清理了。这意味着 viewModelScope 已经取消并调用了 onCleared。这导致了 Combine 发布者比其底层的 StateFlow 集合存活的时间更长。

要解决这个问题,您的 Swift 视图模型应遵守 Cancellable 协议,并在 cancel 函数中执行必要的清理

class TimeTravelViewModel: shared.TimeTravelViewModel, Cancellable {
    func cancel() {
        cancellables = []
    }
}

KMP-ObservableViewModel 将确保在 ViewModel 被清理之前调用 cancel 函数。