Does MailboxProcessor just duplicate IObservable?

限于喜欢 提交于 2021-02-09 10:50:49

问题


I want to process to types of a message

Add x makes program remember number x

Print makes it print all remembered numbers

Why would I write this:

open System
type Message =
    | Add of int
    | Print
let mailbox = new MailboxProcessor<Message>(fun inbox -> 
        let rec loop history = async{
            let! msg=inbox.Receive()
            match msg with
                | Add x -> return! loop(history + x.ToString()+" ")
                | Print ->
                    printfn "%s" history
                    return! loop(history)
        }
        loop ""
    )
[<EntryPoint>]
let main argv = 
    mailbox.Start()
    mailbox.Post(Add 12)
    mailbox.Post(Add 56)
    mailbox.Post(Print)
    mailbox.Post(Add 34)
    mailbox.Post(Print)
    ignore <| Console.ReadLine()
    0

instead of this:

open System
open System.Reactive.Subjects
type Message =
    | Add of int
    | Print
let subject = new Subject<Message>() 
[<EntryPoint>]
let main argv = 
    subject
        |> Observable.scan(fun history msg -> 
                match msg with
                        | Add x -> history + x.ToString()+" "
                        | Print ->
                            printfn "%s" history
                            history
            ) ""
        |> Observable.subscribe(fun _->())
        |> ignore
    subject.OnNext(Add 12)
    subject.OnNext(Add 56)
    subject.OnNext(Print)
    subject.OnNext(Add 34)
    subject.OnNext(Print)
    ignore <| Console.ReadLine()
    0

The MailboxProcessor adds additional level of complexity. I need a state machine which takes a state and returns a state. But it forces me to take inbox, which is used to receive state.

Does it has any advantages to IObservable?


回答1:


No, they're not duplicates of one another. MailboxProcessor and IObservable are low-level building blocks of two different models of computation - actor model and functional reactive programming respectively.

Both deal with asynchronicity, but emphasize different qualities. It's might be possible to build your solution in terms of one or the other - as you noticed in your simple example - but you will find one or the other more natural to use in a particular context.

MailboxProcessors are particularly useful for thread-safe, lock-free access to a resource, such as a file. You can have multiple threads manipulating the resource through an asynchronous interface, and the MailboxProcessor guarantees that only one of those requests is processed at a time.



来源:https://stackoverflow.com/questions/36509538/does-mailboxprocessor-just-duplicate-iobservable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!