KMP-NativeCoroutines
一个从 Kotlin 代码在 KMP 应用中使用 Kotlin 协程库。
想要升级到 0.x 版本?请查阅 迁移步骤。
为什么使用这个库?
虽然 KMP 和 Kotlin 协程都很优秀,但它们组合在一起还有一些限制。
最重要的限制是取消支持。
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-async
、-spm-combine
和-spm-rxswift
的 SPM 特定版本。
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 中的包装函数来获取异步函数、AsyncStreams、Publishers 或 Observables。
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
StateFlows
使用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 协议上不支持扩展函数/属性。*
然而,这种限制可以通过一些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 实现提供了一些函数来为您的协程代码获取 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())
未来
对于暂停函数,您应该使用 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 实现为您的 Coroutines 代码提供了一些获取 Observable
或 Single
的函数。
注意:这些函数创建延迟的
Observable
和Single
这意味着每个订阅都会触发Flow
的收集或挂起函数的执行。
可观察对象
为您的 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
注解添加到生成的属性/函数。
注意:这目前需要一个全局 Opt-in 到
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)
}
}