--- Package examples --- This example demonstrates a Rill pipeline that fetches users from an API, updates their status to active and saves them back. Both operations are performed concurrently. [ForEach] returns on the first error, and context cancellation via defer stops all remaining fetches.
()
| 22 | // Both operations are performed concurrently. |
| 23 | // [ForEach] returns on the first error, and context cancellation via defer stops all remaining fetches. |
| 24 | func Example() { |
| 25 | ctx, cancel := context.WithCancel(context.Background()) |
| 26 | defer cancel() |
| 27 | |
| 28 | // Convert a slice of user IDs into a stream |
| 29 | ids := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil) |
| 30 | |
| 31 | // Read users from the API. |
| 32 | // Concurrency = 3 |
| 33 | users := rill.Map(ids, 3, func(id int) (*mockapi.User, error) { |
| 34 | return mockapi.GetUser(ctx, id) |
| 35 | }) |
| 36 | |
| 37 | // Activate users. |
| 38 | // Concurrency = 2 |
| 39 | err := rill.ForEach(users, 2, func(u *mockapi.User) error { |
| 40 | if u.IsActive { |
| 41 | fmt.Printf("User %d is already active\n", u.ID) |
| 42 | return nil |
| 43 | } |
| 44 | |
| 45 | u.IsActive = true |
| 46 | err := mockapi.SaveUser(ctx, u) |
| 47 | if err != nil { |
| 48 | return err |
| 49 | } |
| 50 | |
| 51 | fmt.Printf("User saved: %+v\n", u) |
| 52 | return nil |
| 53 | }) |
| 54 | |
| 55 | // Handle errors |
| 56 | fmt.Println("Error:", err) |
| 57 | } |
| 58 | |
| 59 | // This example demonstrates a Rill pipeline that fetches users from an API, |
| 60 | // and updates their status to active and saves them back. |