generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
106 lines (85 loc) · 2.36 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package minibus_test
import (
"context"
"fmt"
"time"
"github.com/dogmatiq/minibus"
)
func Example() {
// SayHello is an example message type. Minibus doesn't care what types you
// use for messages, but it's typical to use struct types.
type SayHello struct {
Name string
}
// The recipient function handles SayHello messages.
recipient := func(ctx context.Context) error {
// Subscribe to the types of messages we're interested in.
minibus.Subscribe[SayHello](ctx)
// All functions must signal readiness before messages are exchanged.
minibus.Ready(ctx)
// Handle the messages received on the function's inbox channel. It will
// only receive messages of the same type that it subscribed to.
//
// The inbox channel is closed when ctx.Done() is closed, so it's not
// necessary to select on both.
for m := range minibus.Inbox(ctx) {
switch m := m.(type) {
case SayHello:
fmt.Printf("Hello, %s!\n", m.Name)
// We've said our greetings, let's get out of here.
return nil
}
}
// If the inbox channel was closed before we received the message it
// means we were signalled to stop.
return nil
}
// The sender function sends a SayHello message to the other functions.
sender := func(ctx context.Context) error {
minibus.Ready(ctx)
return minibus.Send(ctx, SayHello{"world"})
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// The Run function executes each function in its own goroutine and
// exchanges messages between them. It blocks until all functions return.
if err := minibus.Run(
ctx,
recipient,
sender,
); err != nil {
fmt.Println(err)
}
// Output:
// Hello, world!
}
func ExampleSubscribe_fireHose() {
recipient := func(ctx context.Context) error {
// Receive everything by subscribing to the [any] interface.
minibus.Subscribe[any](ctx)
minibus.Ready(ctx)
for m := range minibus.Inbox(ctx) {
fmt.Println(m)
}
return nil
}
sender := func(ctx context.Context) error {
minibus.Ready(ctx)
if err := minibus.Send(ctx, "Hello, world!"); err != nil {
return err
}
return minibus.Send(ctx, 42)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
if err := minibus.Run(
ctx,
recipient,
sender,
); err != context.DeadlineExceeded {
fmt.Println(err)
}
// Output:
// Hello, world!
// 42
}