Skip to content

Instantly share code, notes, and snippets.

@AlexZeitler
Forked from isaacabraham/CloudAgent-1.fs
Created June 13, 2021 20:38
Show Gist options
  • Save AlexZeitler/caf136844afc49169b18c9ada10ebad8 to your computer and use it in GitHub Desktop.
Save AlexZeitler/caf136844afc49169b18c9ada10ebad8 to your computer and use it in GitHub Desktop.
Local Mailbox Processor
// Our simple domain model
type Priority =
| Low
| Normal
| High
type Message = {
Text : string
Priority : Priority
}
type MessageCollection =
{ Count : int
Messages : Message list }
type Command =
| Record of Message // Add a new message to file
| Clear // Wipe out all messages
/// Create an Mailbox Processor for a specific actor.
let CreateActor (ActorKey name) =
MailboxProcessor.Start(fun mailbox ->
let messageStore = GetMessageStore name
let rec loop data =
async {
// Wait asynchronously until we get a message
let! message = mailbox.Receive()
// Process the message
match message with
| Clear ->
// Delete file and loop around.
messageStore.DeleteIfExists()
return! loop { Count = 0; Messages = [] }
| Record message ->
// Append the new message to file.
let updatedData =
{ data with
Count = data.Count + 1
Messages = data.Messages @ [ message ] }
messageStore.SetData(updatedData)
return! (loop updatedData)
}
// Start by loading the existing data, then loop indefinitely
let data = defaultArg (messageStore.GetData()) { Count = 0; Messages = [] }
loop data)
// Create an actor and post to it locally
let isaac = CreateActor "isaac"
isaac.Post(Record { Text = "Hello"; Priority = Priority.Low })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment