一个简单且可预测的状态管理库,灵感来源于 Flux + Elm + Redux。 Flywheel 基于 协程 (Corotuines) 构建,并使用 结构化并发 (structured concurrency) 的概念。 其核心在于 有限状态机 (State Machine),该状态机基于 Actor 模型。
目标是使 Redux 的状态管理概念在基于 Kotlin 的项目中变得简单、易懂且易于使用。 为了实现这一目标,我们仅采用了 Redux 的核心概念并稍作修改。 我们排除了 Android、Apple 或任何平台特定的依赖项。 它只是纯 Kotlin。 这样,您可以自由选择最适合您代码库的架构,而无需进行任何大的重构来适应 Flywheel。 不要被它的简单性所迷惑,Flywheel 可以满足您的所有实际用例。 即使我们遗漏了任何东西,它也可以轻松扩展以支持您的用例。
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.msabhi:flywheel:1.1.5-RC")
}
}
}
}
dependencies {
implementation("com.msabhi:flywheel-android:1.1.5-RC")
}
您可以使用 Swift Package Manager,通过将正确的描述添加到您的 Package.swift
文件来安装 Flywheel
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "YOUR_PROJECT_NAME",
dependencies: [
.package(url: "https://github.com/abhimuktheeswarar/Flywheel.git", from: "1.1.5-RC"),
]
)
然后,在准备就绪时运行 swift build
。
这是一个简单的计数器示例。
定义一个状态。
data class CounterState(val counter: Int = 0) : State
定义可以改变状态的动作。
sealed interface CounterAction : Action {
object IncrementAction : CounterAction
object DecrementAction : CounterAction
}
定义一个 reducer,它根据动作和当前状态更新状态。
val reduce = reducerForAction<CounterAction, CounterState> { action, state ->
with(state) {
when (action) {
is CounterAction.IncrementAction -> copy(counter = counter + 1)
is CounterAction.DecrementAction -> copy(counter = counter - 1)
}
}
}
创建一个 StateReserve。
val stateReserve = StateReserve(
initialState = InitialState.set(CounterState()),
reduce = reduce)
监听状态变化
stateReserve.states.collect { state -> println(state.counter) }
将动作发送到 StateReserve 以更新状态。
stateReserve.dispatch(IncrementAction)
Copyright (C) 2021 Abhi Muktheeswarar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://apache.ac.cn/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.