KMP-NativeCoroutines
这是一个库,允许在KMP应用程序中从Swift代码中使用Kotlin Coroutines。
正在从0.x版本升级?请查看迁移步骤。
为何使用这个库?
KMP和Kotlin Coroutines都非常出色,但它们有一些限制。
最重要的限制是取消支持。
Kotlin挂起函数以带有完成处理程序的功能的形式暴露给Swift。
这允许您轻松从Swift代码中使用它们,但它不支持取消。
注意:虽然Swift 5.5将异步函数引入Swift,但它并没有解决这个问题。
为了与ObjC互操作性,所有带有完成处理程序的功能都可以像一个异步函数一样调用。
这意味着从Swift 5.5开始,您的Kotlin挂起函数将看起来像Swift异步函数。
但这只是语法糖,因此仍然没有取消支持。
此外,ObjC不支持在协议中泛型。
因此,所有Flow
接口都失去了其泛型值类型,这使得它们难以使用。
这个库解决了这两个限制
兼容性
库的最新版本使用 Kotlin 版本 1.9.0
。
还提供适用于较旧版本和/或预览版 Kotlin 的兼容性版本
版本 | 版本后缀 | Kotlin | KSP | 协程 |
---|---|---|---|---|
最新版本 | 无后缀 | 1.9.0 | 1.0.12 | 1.7.3 |
1.0.0-ALPHA-13 | 无后缀 | 1.9.0 | 1.0.11 | 1.7.2 |
1.0.0-ALPHA-12 | 无后缀 | 1.8.22 | 1.0.11 | 1.7.2 |
1.0.0-ALPHA-10 | 无后缀 | 1.8.21 | 1.0.11 | 1.7.1 |
1.0.0-ALPHA-8 | 无后缀 | 1.8.21 | 1.0.11 | 1.6.4 |
1.0.0-ALPHA-7 | 无后缀 | 1.8.20 | 1.0.10 | 1.6.4 |
1.0.0-ALPHA-5 | 无后缀 | 1.8.10 | 1.0.9 | 1.6.4 |
1.0.0-ALPHA-4 | 无后缀 | 1.8.0 | 1.0.8 | 1.6.4 |
您可以从几个 Swift 实现中选择。
根据实现,您可以支持至少 iOS 9、macOS 10.9、tvOS 9 和 watchOS 3
实现 | Swift | iOS | macOS | tvOS | watchOS |
---|---|---|---|---|---|
异步 | 5.5 | 13.0 | 10.15 | 13.0 | 6.0 |
Combine | 5.0 | 13.0 | 10.15 | 13.0 | 6.0 |
RxSwift | 5.0 | 9.0 | 10.9 | 9.0 | 3.0 |
安装
库由 Kotlin 和 Swift 部分组成,您需要将其添加到您的项目中。
Kotlin 部分可在 Maven Central 获取,Swift 部分可通过 CocoaPods 或 Swift 包管理器安装。
请确保始终为所有库使用相同的版本!
Kotlin
对于 Kotlin,请将插件添加到您的 build.gradle.kts
plugins {
id("com.google.devtools.ksp") version "1.9.0-1.0.12"
id("com.rickclephas.kmp.nativecoroutines") version "1.0.0-ALPHA-14"
}
并确保选择实验性的 @ObjCName
注解
kotlin.sourceSets.all {
languageSettings.optIn("kotlin.experimental.ExperimentalObjCName")
}
Swift (Swift Package Manager)
Swift 实现可以通过 Swift 包管理器获得。
只需将其添加到您的 Package.swift
文件中。
dependencies: [
.package(url: "https://github.com/rickclephas/KMP-NativeCoroutines.git", from: "1.0.0-ALPHA-14")
]
或者在 Xcode 中添加,通过前往 文件
> 添加包...
并提供以下 URL: https://github.com/rickclephas/KMP-NativeCoroutines.git
。
注意:Swift 包的版本不应包含 Kotlin 版本后缀(例如
-new-mm
或-kotlin-1.6.0
)。
注意:如果您只需要单个实现,您还可以使用 SPM 特定的版本,后缀为
-spm-async
、-spm-combine
和-spm-rxswift
。
Swift (CocoaPods)
如果您使用 CocoaPods,请将以下库之一添加到您的 Podfile
中。
pod 'KMPNativeCoroutinesAsync', '1.0.0-ALPHA-14' # Swift Concurrency implementation
pod 'KMPNativeCoroutinesCombine', '1.0.0-ALPHA-14' # Combine implementation
pod 'KMPNativeCoroutinesRxSwift', '1.0.0-ALPHA-14' # RxSwift implementation
注意:CocoaPods 的版本不应包含 Kotlin 版本后缀(例如
-new-mm
或-kotlin-1.6.0
)。
用法
从 Swift 中使用 Kotlin 协程代码几乎与调用 Kotlin 代码一样简单。
只需在 Swift 中使用包装函数来获取异步函数、异步流、发布者或观察者。
Kotlin
插件将自动为您生成所需的代码!
只需在协程声明上添加 @NativeCoroutines
(或 @NativeCoroutinesState
)注解。
流
您的 Flow
属性/函数将获得本地版本
import com.rickclephas.kmp.nativecoroutines.NativeCoroutines
class Clock {
// Somewhere in your Kotlin code you define a Flow property
// and annotate it with @NativeCoroutines
@NativeCoroutines
val time: StateFlow<Long> // This can be any kind of Flow
}
生成的代码
插件将为您生成此本地属性
import com.rickclephas.kmp.nativecoroutines.asNativeFlow
import kotlin.native.ObjCName
@ObjCName(name = "time")
val Clock.timeNative
get() = time.asNativeFlow()
对于上方定义的 StateFlow
,插件还会生成此值属性
val Clock.timeValue
get() = time.value
如果是 SharedFlow
,插件将生成回放缓存属性
val Clock.timeReplayCache
get() = time.replayCache
StateFlow
使用 StateFlow
属性跟踪状态(如视图模型中)?
请使用 @NativeCoroutinesState
注解
import com.rickclephas.kmp.nativecoroutines.NativeCoroutinesState
class Clock {
// Somewhere in your Kotlin code you define a StateFlow property
// and annotate it with @NativeCoroutinesState
@NativeCoroutinesState
val time: StateFlow<Long> // This must be a StateFlow
}
生成的代码
插件将为您生成这些本地属性
import com.rickclephas.kmp.nativecoroutines.asNativeFlow
import kotlin.native.ObjCName
@ObjCName(name = "time")
val Clock.timeValue
get() = time.value
val Clock.timeFlow
get() = time.asNativeFlow()
挂起函数
插件还为您生成了注解挂起函数的本地版本
import com.rickclephas.kmp.nativecoroutines.NativeCoroutines
class RandomLettersGenerator {
// Somewhere in your Kotlin code you define a suspend function
// and annotate it with @NativeCoroutines
@NativeCoroutines
suspend fun getRandomLetters(): String {
// Code to generate some random letters
}
}
生成的代码
插件将为您生成此本地函数
import com.rickclephas.kmp.nativecoroutines.nativeSuspend
import kotlin.native.ObjCName
@ObjCName(name = "getRandomLetters")
fun RandomLettersGenerator.getRandomLettersNative() =
nativeSuspend { getRandomLetters() }
接口限制
不幸的是,扩展函数/属性在 Objective-C 协议中不支持[链接](https://kotlinlang.org/docs/native-objc-interop.html#extensions-and-category-members)。
但是,可以通过一些 Swift 魔法克服这个限制。
假设 RandomLettersGenerator
是一个 interface
而不是一个 class
,我们可以这样做
import KMPNativeCoroutinesCore
extension RandomLettersGenerator {
func getRandomLetters() -> NativeSuspend<String, Error, KotlinUnit> {
RandomLettersGeneratorNativeKt.getRandomLetters(self)
}
}
Swift 并发
Async 实现提供了一些函数来获取异步 Swift 函数和 AsyncSequence
。
Async 函数
使用 asyncFunction(for:)
函数获取可等待的异步函数
import KMPNativeCoroutinesAsync
let handle = Task {
do {
let letters = try await asyncFunction(for: randomLettersGenerator.getRandomLetters())
print("Got random letters: \(letters)")
} catch {
print("Failed with error: \(error)")
}
}
// To cancel the suspend function just cancel the async task
handle.cancel()
或者如果你不喜欢这些 do-catches,可以使用 asyncResult(for:)
函数
import KMPNativeCoroutinesAsync
let result = await asyncResult(for: randomLettersGenerator.getRandomLetters())
if case let .success(letters) = result {
print("Got random letters: \(letters)")
}
AsyncSequence
对于 Flow
,有 asyncSequence(for:)
函数来获取 AsyncSequence
import KMPNativeCoroutinesAsync
let handle = Task {
do {
let sequence = asyncSequence(for: randomLettersGenerator.getRandomLettersFlow())
for try await letters in sequence {
print("Got random letters: \(letters)")
}
} catch {
print("Failed with error: \(error)")
}
}
// To cancel the flow (collection) just cancel the async task
handle.cancel()
Combine
Combine 实现提供了一组函数来获取为你的 Coroutines 代码创建的 AnyPublisher
注意:这些函数创建延迟的
AnyPublisher
这意味着每个订阅都会触发Flow
的收集或挂起函数的执行。
发布者
为您使用 Flow
时,请使用 createPublisher(for:)
函数
import KMPNativeCoroutinesCombine
// Create an AnyPublisher for your flow
let publisher = createPublisher(for: clock.time)
// Now use this publisher as you would any other
let cancellable = publisher.sink { completion in
print("Received completion: \(completion)")
} receiveValue: { value in
print("Received value: \(value)")
}
// To cancel the flow (collection) just cancel the publisher
cancellable.cancel()
您还可以为返回 Flow
的暂停函数使用 createPublisher(for:)
函数
let publisher = createPublisher(for: randomLettersGenerator.getRandomLettersFlow())
Future
对于暂停函数,应使用 createFuture(for:)
函数
import KMPNativeCoroutinesCombine
// Create a Future/AnyPublisher for the suspend function
let future = createFuture(for: randomLettersGenerator.getRandomLetters())
// Now use this future as you would any other
let cancellable = future.sink { completion in
print("Received completion: \(completion)")
} receiveValue: { value in
print("Received value: \(value)")
}
// To cancel the suspend function just cancel the future
cancellable.cancel()
RxSwift
RxSwift 实现提供几个函数来获取您的协程代码的 Observable
或 Single
。
注意:这些函数会创建延迟的
Observable
和Single
。
这意味着每个订阅都会触发Flow
的收集或挂起函数的执行。
Observable
对于您的 Flow
,请使用 createObservable(for:)
函数
import KMPNativeCoroutinesRxSwift
// Create an observable for your flow
let observable = createObservable(for: clock.time)
// Now use this observable as you would any other
let disposable = observable.subscribe(onNext: { value in
print("Received value: \(value)")
}, onError: { error in
print("Received error: \(error)")
}, onCompleted: {
print("Observable completed")
}, onDisposed: {
print("Observable disposed")
})
// To cancel the flow (collection) just dispose the subscription
disposable.dispose()
您还可以为返回 Flow
的暂停函数使用 createObservable(for:)
函数
let observable = createObservable(for: randomLettersGenerator.getRandomLettersFlow())
单例
对于挂起函数,您应使用 createSingle(for:)
函数
import KMPNativeCoroutinesRxSwift
// Create a single for the suspend function
let single = createSingle(for: randomLettersGenerator.getRandomLetters())
// Now use this single as you would any other
let disposable = single.subscribe(onSuccess: { value in
print("Received value: \(value)")
}, onFailure: { error in
print("Received error: \(error)")
}, onDisposed: {
print("Single disposed")
})
// To cancel the suspend function just dispose the subscription
disposable.dispose()
自定义
您可以通过多种方式自定义生成的 Kotlin 代码。
名称后缀
不喜欢生成的属性/函数的命名吗?
在您的 build.gradle.kts
文件中指定您自己的自定义后缀。
nativeCoroutines {
// The suffix used to generate the native coroutine function and property names.
suffix = "Native"
// The suffix used to generate the native coroutine file names.
// Note: defaults to the suffix value when `null`.
fileSuffix = null
// The suffix used to generate the StateFlow value property names,
// or `null` to remove the value properties.
flowValueSuffix = "Value"
// The suffix used to generate the SharedFlow replayCache property names,
// or `null` to remove the replayCache properties.
flowReplayCacheSuffix = "ReplayCache"
// The suffix used to generate the native state property names.
stateSuffix = "Value"
// The suffix used to generate the `StateFlow` flow property names,
// or `null` to remove the flow properties.
stateFlowSuffix = "Flow"
}
CoroutineScope
为了获得更多控制,您可以使用带有 NativeCoroutineScope
注解的自定义 CoroutineScope
import com.rickclephas.kmp.nativecoroutines.NativeCoroutineScope
class Clock {
@NativeCoroutineScope
internal val coroutineScope = CoroutineScope(job + Dispatchers.Default)
}
注意:您的自定义协程作用域必须为
internal
或public
。
如果您不提供 CoroutineScope
,将默认使用作用域,其定义如下
internal val defaultCoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
注意:KMP-NativeCoroutines 内置了对 KMM-ViewModel 的支持。
您在KMMViewModel
中编写的协程将(默认情况下)使用来自ViewModelScope
的CoroutineScope
。
忽略声明
使用NativeCoroutinesIgnore
注释来告诉插件忽略一个属性或函数
import com.rickclephas.kmp.nativecoroutines.NativeCoroutinesIgnore
@NativeCoroutinesIgnore
val ignoredFlowProperty: Flow<Int>
@NativeCoroutinesIgnore
suspend fun ignoredSuspendFunction() { }
在Swift中细化声明
如果出于某些原因你想在Swift中进一步细化你的Kotlin声明,可以使用NativeCoroutinesRefined
和NativeCoroutinesRefinedState
注释。
这将告诉插件将ShouldRefineInSwift
注释添加到生成的属性或函数中。
注意:这目前需要一个模块级别的
kotlin.experimental.ExperimentalObjCRefinement
接受。
例如,您可以将您的Flow
属性细化为一个AnyPublisher
属性
import com.rickclephas.kmp.nativecoroutines.NativeCoroutinesRefined
class Clock {
@NativeCoroutinesRefined
val time: StateFlow<Long>
}
import KMPNativeCoroutinesCombine
extension Clock {
var time: AnyPublisher<KotlinLong, Error> {
createPublisher(for: __time)
}
}