Skip to content

Commit c7cded8

Browse files
authored
Add select example
1 parent 87784a8 commit c7cded8

File tree

1 file changed

+86
-2
lines changed

1 file changed

+86
-2
lines changed

README.md

Lines changed: 86 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ Borrows heavily from [Temporal](https://github.com/temporalio/temporal) (and sin
66

77
Note on go1.18 generics: many of the `Get(...)` operations will become easier with generics, an ongoing exploration is happening in branch [go118](https://github.com/cschleiden/go-workflows/tree/go118).
88

9-
See also:
10-
- https://cschleiden.dev/blog/2022-02-13-go-workflows-part1/
9+
See also:
10+
- https://cschleiden.dev/blog/2022-02-13-go-workflows-part1/
1111

1212
## Simple example
1313

@@ -315,6 +315,90 @@ if err != nil {
315315
}
316316
```
317317
318+
### `select`
319+
320+
Due its non-deterministic behavior you must not use a `select` statement in workflows. Instead you can use the provided `workflow.Select` function. It blocks until one of the provided cases is ready. Cases are evaluated in the order passed to `Select.
321+
322+
```go
323+
var f1 workflow.Future
324+
var c workflow.Channel
325+
326+
workflow.Select(
327+
ctx,
328+
workflow.Await(f1, func (ctx workflow.Context, f Future) {
329+
var r int
330+
err := f.Get(ctx, &r)
331+
// ...
332+
}),
333+
workflow.Receive(c, func (ctx workflow.Context, c Channel) {
334+
v, _ := c.Receive(ctx)
335+
// ...
336+
}),
337+
workflow.Default(ctx, func (ctx workflow.Context) {
338+
// ...
339+
})
340+
)
341+
```
342+
343+
#### Waiting for a Future
344+
345+
`Await` adds a case to wait for a Future to have a value
346+
347+
```go
348+
var f1, f2 workflow.Future
349+
350+
workflow.Select(
351+
ctx,
352+
workflow.Await(f1, func (ctx workflow.Context, f Future) {
353+
var r int
354+
err := f.Get(ctx, &r)
355+
// ...
356+
}),
357+
workflow.Await(f2, func (ctx workflow.Context, f Future) {
358+
var r int
359+
err := f.Get(ctx, &r)
360+
// ...
361+
}),
362+
)
363+
```
364+
365+
#### Waiting to receive from a Channel
366+
367+
`Receive` adds a case to receive from a given channel
368+
369+
```go
370+
var c workflow.Channel
371+
372+
workflow.Select(
373+
ctx,
374+
workflow.Receive(c, func (ctx workflow.Context, c Channel) {
375+
v, _ := c.Receive(ctx)
376+
// ...
377+
}),
378+
)
379+
```
380+
381+
#### Default/Non-blocking
382+
383+
A `Default` case is executed if no previous case is ready and selected:
384+
385+
```go
386+
var f1 workflow.Future
387+
388+
workflow.Select(
389+
ctx,
390+
workflow.Await(f1, func (ctx workflow.Context, f Future) {
391+
var r int
392+
err := f.Get(ctx, &r)
393+
// ...
394+
}),
395+
workflow.Default(ctx, func (ctx workflow.Context) {
396+
// ...
397+
})
398+
)
399+
```
400+
401+
318402
#### Perform any cleanup
319403

320404
```go

0 commit comments

Comments
 (0)