Skip to content

Instantly share code, notes, and snippets.

@Youenn-Bouglouan
Created August 17, 2017 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Youenn-Bouglouan/3d0ae88a1ef43deccf0eac339a2f5ad8 to your computer and use it in GitHub Desktop.
Save Youenn-Bouglouan/3d0ae88a1ef43deccf0eac339a2f5ad8 to your computer and use it in GitHub Desktop.
Akka.NET / Handling messages in F#
open System
open Akka.Actor
open Akka.FSharp
type ActorAMessages =
| MessageA1 of name: string
| MessageA2 of quantity: int
| MessageA3
type ActorBMessages =
| MessageB1 of weight: float
| MessageB2 of dimensions: float * float * float
// mailbox will be of type Actor<ActorAMessages>
let actorA (mailbox: Actor<_>) =
let rec loop () = actor {
let! message = mailbox.Receive ()
match message with
| MessageA1 name -> ()
| MessageA2 quantity -> ()
| MessageA3 -> ()
return! loop ()
}
loop ()
// mailbox will be of type Actor<ActorBMessages>
let actorB (mailbox: Actor<_>) =
let rec loop () = actor {
let! message = mailbox.Receive ()
match message with
| MessageB1 weight -> ()
| MessageB2 (l, w, d) -> ()
return! loop ()
}
loop ()
// mailbox will be of type Actor<ActorAMessages> (first branch of the match expression)
let actorC (mailbox: Actor<_>) =
let rec loop () = actor {
let! message = mailbox.Receive ()
match message with
| MessageA1 name -> () // handle message of type ActorAMessages
//| MessageB2 (l, w, d) -> () // cannot handle MessageB2 here, compilation error!
//| ...
return! loop ()
}
loop ()
// *** Solution 1: aggregate messages ***
type AggregateMessages =
| MessageA of ActorAMessages
| MessageB of ActorBMessages
// mailbox will be of type Actor<AggregateMessages>
let actorC' (mailbox: Actor<_>) =
let rec loop () = actor {
let! message = mailbox.Receive ()
match message with
| MessageA messageA -> // handle ActorAMessages
match messageA with
| MessageA1 name -> ()
| MessageA3 -> ()
| MessageB messageB -> // handle ActorBMessages
match messageB with
| MessageB2 (l, w, d) -> ()
return! loop ()
}
loop ()
// *** Solution 2: new type with duplicate ***
type ActorCMessages =
| MessageA1 of name: string
| MessageA3
| MessageB2 of dimensions: float * float * float
// mailbox will be of type Actor<ActorCMessages>
let actorC'' (mailbox: Actor<_>) =
let rec loop () = actor {
let! message = mailbox.Receive ()
match message with
| MessageA1 name -> () // do something with name
| MessageA3 -> ()
| MessageB2 (l, w, d) -> ()
return! loop ()
}
loop ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment