gpt4 book ai didi

kotlin - 如何在函数式编程中处理私有(private)状态?

转载 作者:行者123 更新时间:2023-12-02 09:20:38 26 4
gpt4 key购买 nike

我的应用程序中有一个功能,其中包含一些私有(private)状态信息和一些要共享的公共(public)状态。如何摆脱可变的私有(private)状态变量?如何将私有(private)状态纳入链中?

我最近刚刚了解了函数式编程,并希望将此功能转换为更像 fp 的方法。

这是我迄今为止的方法,作为一个简单的示例。

sealed class PublicState {
data class Data(val a:Int, val b:Int):PublicState()
object Pending : PublicState()
}

data class PrivateState(val a:Int, val b:Int, val x:Int)

sealed class Action {
data class InputC(val c:Int):Action()
data class InputD(val d:Int):Action()
}

sealed class Update {
data class A(val a:Int):Update()
data class B(val b:Int):Update()
object Working : Update()
}

class Feature {

val actions = PublishSubject.create<Action>()
val state = BehaviorSubject.create<PublicState>()

private var privateState = PrivateState(0,0,1)

init {
val startState = privateState.toPublicState()
actions.flatMap {action ->
when (action) {
is Action.InputC -> handleC(action)
is Action.InputD -> handleD(action)
}
}.scan(startState, ::reduce)
.subscribe(state)
}

fun reduce(previousState:PublicState, update: Update):PublicState {

// can't use previousState because Pending has not all information
// I don't want to add the information to pending because state is undefined while pending
return when (update) {

is Update.A -> privateState.copy(a = update.a).toPublicState()
is Update.B -> privateState.copy(b = update.b).toPublicState()
Update.Working -> PublicState.Pending
}
}

fun doAction(action: Action) {
actions.onNext(action)
}

private fun handleC(action:Action.InputC):Observable<Update> {
return Observable.fromCallable {
// time consuming work which uses x
val result = privateState.x + privateState.a + action.c
Update.A(result) as Update
}.startWith(Update.Working)
}

private fun handleD(action:Action.InputD):Observable<Update> {
return Observable.fromCallable {
// time consuming work which uses x
val result = privateState.x + privateState.b + action.d
Update.B(result) as Update
}.startWith(Update.Working)
}

}

private fun PrivateState.toPublicState(): PublicState {
return PublicState.Data(a, b)
}

实际上,状态变量比 a、b 和 x 要多得多。但如果我希望它们在链中,我就有一个巨大的 State 变量,并且所有这些变量都会暴露出来。使用可变变量感觉更容易。您对如何解决这个问题有什么建议吗?如果您认为这是错误的方法,我也欢迎其他模式。我的目标是保留一些私有(private)状态并仅公开 PublicState。

最佳答案

FP 不与私有(private)国家打交道。你为什么要关心保密?因为来自外部世界的其他人可能有意或无意地变异那个物体并使整个物体失修,对吗?但 FP 中没有突变。所以你很安全。

因此,您的问题简化为“如何处理状态”。好吧,如果您想让我回答,请告诉我。

关于kotlin - 如何在函数式编程中处理私有(private)状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com