github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/actor/actor_example_test.go (about) 1 package actor_test 2 3 import ( 4 "fmt" 5 "sync" 6 "time" 7 8 "github.com/asynkron/protoactor-go/actor" 9 ) 10 11 // Demonstrates how to create an actor using a function literal and how to send a message asynchronously 12 func Example() { 13 context := system.Root 14 props := actor.PropsFromFunc(func(c actor.Context) { 15 if msg, ok := c.Message().(string); ok { 16 fmt.Println(msg) // outputs "Hello World" 17 } 18 }) 19 20 pid := context.Spawn(props) 21 22 context.Send(pid, "Hello World") 23 time.Sleep(time.Millisecond * 100) 24 25 _ = context.StopFuture(pid).Wait() // wait for the actor to stop 26 27 // Output: Hello World 28 } 29 30 // Demonstrates how to send a message from one actor to another and for the caller to wait for a response before 31 // proceeding 32 func Example_synchronous() { 33 var wg sync.WaitGroup 34 35 wg.Add(1) 36 37 // callee will wait for the PING message 38 callee := system.Root.Spawn(actor.PropsFromFunc(func(c actor.Context) { 39 if msg, ok := c.Message().(string); ok { 40 fmt.Println(msg) // outputs PING 41 c.Respond("PONG") 42 } 43 })) 44 45 // caller will send a PING message and wait for the PONG 46 caller := system.Root.Spawn(actor.PropsFromFunc(func(c actor.Context) { 47 switch msg := c.Message().(type) { 48 // the first message an actor receives after it has started 49 case *actor.Started: 50 // send a PING to the callee, and specify the response 51 // is sent to Self, which is this actor'pids PID 52 c.Request(callee, "PING") 53 54 case string: 55 fmt.Println(msg) // PONG 56 wg.Done() 57 } 58 })) 59 60 wg.Wait() 61 _ = system.Root.StopFuture(callee).Wait() 62 _ = system.Root.StopFuture(caller).Wait() 63 64 // Output: 65 // PING 66 // PONG 67 }