Hi I'm learning goroutine, and I have a question I have a code where I have a publisher and a listener, I need the subscribe call to happen first then the publish call.
useCase := New(tt.fields.storage)
tt.fields.wg.Add(1)
go func() {
ch, _, err := useCase.Subscribe(tt.args.ctx, tt.args.message.TopicName)
message, ok := <- ch
if !ok {
close(ch)
tt.fields.wg.Done()
}
require.NoError(t, err)
assert.Equal(t, tt.want, message)
}()
err := useCase.Publish(tt.args.ctx, tt.args.message)
tt.fields.wg.Wait()
and as I send messages inside these two functions I need Go Func, how would I get subscribe to always execute first, and then publish.
CodePudding user response:
You can use a channel:
subscribed:=make(chan struct{})
go func() {
ch, _, err := useCase.Subscribe(tt.args.ctx, tt.args.message.TopicName)
if err!=nil {
...
}
close(subscribed)
message, ok := <- ch
...
}()
<-subscribed
err := useCase.Publish(tt.args.ctx, tt.args.message)