【问题标题】:How can i wait for multiple signals on same channel in temporal golang我如何在时间 golang 中等待同一通道上的多个信号
【发布时间】:2022-12-10 12:00:15
【问题描述】:

我的工作流程中有一个切片,需要等到我在同一信号通道上收到切片中每个元素的信号。我尝试使用以下代码,但它似乎没有等待收到的所有消息。

        selector := workflow.NewSelector(ctx)
        notificationSignalChan := workflow.GetSignalChannel(ctx, "my-channel")

        for i := 0; i < len(container.Items); i++ {
            if container.Items[i].Status != status.Pending {
                continue
            }

            var expectedNotification events.Notification

            selector.AddReceive(notificationSignalChan, func(c workflow.ReceiveChannel, more bool) {
                // So it has to be explicitly consumed here
                c.Receive(ctx, &expectedNotification)
                idx := slices.IndexFunc(container.Items, func(item *model.Item) bool {
                    return item.ID == notification.ItemID
                })
                
                recordedAt := workflow.Now(ctx)
                container.Items[idx].Status = status.Processed
                err = workflow.ExecuteActivity(ctx, activities.OnProcessed, container.Items[idx]).Get(ctx, nil)
                
                if err != nil {
                    panic(err)
                }
            })
        }
        
        for i := 0; i < len(container.Items); i++ {
            if container.Items[i].Status != status.Pending {
                continue
            }

            selector.Select(ctx)
        }


【问题讨论】:

    标签: go temporal


    【解决方案1】:

    你可以有一个无限循环和一个 select 语句,所以当你从通道中得到一个对象时,只需与列表中的项目进行比较并从列表中删除该项目,检查列表中是否有任何项目继续,否则只需中断 for 循环。

    for {
        select {
        case data := <-signal:
            for idx, obj := range lst {
                if data == obj {
                    // do your staff
                    fmt.Println(data)
    
                    // remove that item from list
                    if len(lst) <= 1 {
                        return
                    }
                    lst = append(lst[:idx], lst[idx+1:]...)
                    // break the inner loop
                    break
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-11
      • 2014-01-02
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多