Skip to content

Commit

Permalink
Storing ctx on a struct is bad
Browse files Browse the repository at this point in the history
Summary:
Not idiomatic.

> Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it.

As per: https://pkg.go.dev/context

Reviewed By: podtserkovskiy

Differential Revision: D67216776

fbshipit-source-id: e67d1f6ceaa8a1f5693e03c3e0f911ae0a34f238
  • Loading branch information
echistyakov authored and facebook-github-bot committed Dec 14, 2024
1 parent c0df0e0 commit 645e763
Showing 1 changed file with 7 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,23 @@ import (
func rsocketBlock(ctx context.Context, client rsocket.Client, request payload.Payload) (payload.Payload, error) {
mono := client.RequestResponse(request)
// This implementation of subscriber avoids race conditions on close that is present in the default implementation in the rsocket library.
s := newSubscriber(ctx)
mono.SubscribeWith(ctx, s)
return s.Block()
sub := newSubscriber()
mono.SubscribeWith(ctx, sub)
return sub.Block(ctx)
}

type subsriber struct {
errChan chan error
valChan chan payload.Payload
completeChan chan struct{}
ctx context.Context
cancelSubscription func()
}

func newSubscriber(ctx context.Context) *subsriber {
func newSubscriber() *subsriber {
return &subsriber{
errChan: make(chan error, 1),
valChan: make(chan payload.Payload, 1),
completeChan: make(chan struct{}, 1),
ctx: ctx,
}
}

Expand Down Expand Up @@ -76,7 +74,7 @@ func (s *subsriber) OnSubscribe(ctx context.Context, subscription rx.Subscriptio
}
}

func (s *subsriber) Block() (payload.Payload, error) {
func (s *subsriber) Block(ctx context.Context) (payload.Payload, error) {
var val payload.Payload
for {
select {
Expand All @@ -85,8 +83,8 @@ func (s *subsriber) Block() (payload.Payload, error) {
case val = <-s.valChan:
case <-s.completeChan:
return val, nil
case <-s.ctx.Done():
return val, s.ctx.Err()
case <-ctx.Done():
return val, ctx.Err()
}
}
}

0 comments on commit 645e763

Please sign in to comment.