Ada*_*ley 5 f# mutable observer-pattern
我目前正在重新开发F#中的应用程序,虽然经验非常出色,但在控制可变性时我发现自己有点困惑.
以前,我的C#程序使用的文档模型是高度可变的,并实现了ObservableCollections和INotifyPropertyChanged,它们之间的共享状态不会出错.显然,这不是一个理想的选择,特别是如果我想要一个完全不可改变的设计方法.
考虑到这一点,我为我的底层应用程序内核创建了一个不可观察的,不可变的文档模型,但是,因为我希望UI订阅者看到更改,我立即发现自己实现了事件驱动模式:
// Raw data.
type KernelData = { DocumentContent : List<string> }
// Commands that act on the data.
type KernelCommands = { AddString : string -> () }
// A command implementation. Performs a state change, echos the new state through the event.
let addStringCommand (kernelState : KernelData) (kernelChanged : Event<KernelData>) (newString : string) =
kernelState with { DocumentContent=oldList |> List.add newString }
|> kernelChanged.Trigger
// Time to wire this up.
do
// Create some starting state.
let kernelData = { DocumentContent=List.Empty }
// Create a shared event that commands may use to inform observers (UI).
let kernelChangedEvent = new Event<KernelData>()
// Create the command, it uses the event to inform observers.
let kernelCommands = { AddString=addString kernelData kernelChangedEvent }
// Create a UI element that uses the commands to initialize data transformations. UI elements subscribed to the data use the event to listen.
let myUI = new UiObject(kernelData, kernelChangedEvent.Publish, kernelCommands)
myUI.Show()
Run Code Online (Sandbox Code Playgroud)
所以这是我将新状态传递给相关听众的解决方案.然而,更理想的是一个"盒子",我可以用变换函数"挂钩".当框变异时,调用函数来处理新状态并在UI组件中产生相应的更改状态.
do
// Lambda called whenever the box changes.
idealBox >>= (fun newModel -> new UIComponent(newModel))
Run Code Online (Sandbox Code Playgroud)
所以我想我在问是否有一种可观察的模式来处理这些情况.可变状态通常使用monad处理,但我只看到涉及执行操作的示例(例如管道控制台IO monad,加载文件等),而不是实际处理持续变异状态.
我针对这些场景的一般解决方案是在纯功能设置中构建所有业务逻辑,然后提供一个具有同步和传播更改所需功能的瘦服务层。以下是适合您的类型的纯接口示例KernelData:
type KernelData = { DocumentContent : List<string> }
let emptyKernelData = {DocumentContent = []}
let addDocument c kData = {kData with DocumentContent = c :: kData.DocumentContent}
Run Code Online (Sandbox Code Playgroud)
然后,我将定义一个服务层接口,其中包含修改和订阅更改的功能:
type UpdateResult =
| Ok
| Error of string
/// Service interface
type KernelService =
{
/// Gets the current kernel state.
Current : unit -> KernelData
/// Subscribes to state changes.
Subscribe : (KernelData -> unit) -> IDisposable
/// Modifies the current kernel state.
Modify : (KernelData -> KernelData) -> Async<UpdateResult>
}
Run Code Online (Sandbox Code Playgroud)
这些Async响应启用非阻塞更新。该UpdateResult类型用于指示更新操作是否成功。为了构建一个健全的KernelService对象,重要的是要认识到修改请求需要同步以避免并行更新造成的数据丢失。为此目的MailboxProcessors 派上用场。这是一个buildKernelService函数,它构造一个给定初始值的服务接口KernelData。
// Builds a service given an initial kernel data value.
let builKernelService (def: KernelData) =
// Keeps track of the current kernel data state.
let current = ref def
// Keeps track of update events.
let changes = new Event<KernelData>()
// Serves incoming requests for getting the current state.
let currentProc : MailboxProcessor<AsyncReplyChannel<KernelData>> =
MailboxProcessor.Start <| fun inbox ->
let rec loop () =
async {
let! chn = inbox.Receive ()
chn.Reply current.Value
return! loop ()
}
loop ()
// Serves incoming 'modify requests'.
let modifyProc : MailboxProcessor<(KernelData -> KernelData) * AsyncReplyChannel<UpdateResult>> =
MailboxProcessor.Start <| fun inbox ->
let rec loop () =
async {
let! f, chn = inbox.Receive ()
let v = current.Value
try
current := f v
changes.Trigger current.Value
chn.Reply UpdateResult.Ok
with
| e ->
chn.Reply (UpdateResult.Error e.Message)
return! loop ()
}
loop ()
{
Current = fun () -> currentProc.PostAndReply id
Subscribe = changes.Publish.Subscribe
Modify = fun f -> modifyProc.PostAndAsyncReply (fun chn -> f, chn)
}
Run Code Online (Sandbox Code Playgroud)
请注意,上面的实现中没有什么是独特的KernelData因此服务接口以及构建函数可以泛化为任意类型的内部状态。
最后,一些编程示例KernelService:
// Build service object.
let service = builKernelService emptyKernelData
// Print current value.
let curr = printfn "Current state: %A" service.Current
// Subscribe
let dispose = service.Subscribe (printfn "New State: %A")
// Non blocking update adding a document
service.Modify <| addDocument "New Document 1"
// Non blocking update removing all existing documents.
service.Modify (fun _ -> emptyKernelData)
// Blocking update operation adding a document.
async {
let! res = service.Modify (addDocument "New Document 2")
printfn "Update Result: %A" res
return ()
}
|> Async.RunSynchronously
// Blocking update operation eventually failing.
async {
let! res =
service.Modify (fun kernelState ->
System.Threading.Thread.Sleep 10000
failwith "Something terrible happened"
)
printfn "Update Result: %A" res
return ()
}
|> Async.RunSynchronously
Run Code Online (Sandbox Code Playgroud)
除了更多的技术细节之外,我相信与原始解决方案最重要的区别是不需要特殊的命令功能。使用服务层,任何在其上运行的纯函数KernelData(例如addDocument)都可以使用该Modify函数提升为有状态计算。