Created
February 14, 2020 21:50
-
-
Save dragonsinth/a46851917553a7b17e47f44090ea23e1 to your computer and use it in GitHub Desktop.
GetFriends using select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func GetFriends(ctx context.Context, user int64) (map[string]*User, error) { | |
g, ctx := errgroup.WithContext(ctx) | |
friendIds := make(chan int64) | |
// Produce | |
g.Go(func() error { | |
defer close(friendIds) | |
for it := GetFriendIds(user); ; { | |
if id, err := it.Next(ctx); err != nil { | |
if err == io.EOF { | |
return nil | |
} | |
return fmt.Errorf("GetFriendIds %d: %s", user, err) | |
} else { | |
select { | |
case <-ctx.Done(): | |
return ctx.Err() | |
case friendIds <- id: | |
} | |
} | |
} | |
}) | |
friends := make(chan *User) | |
// Map | |
workers := int32(nWorkers) | |
for i := 0; i < nWorkers; i++ { | |
g.Go(func() error { | |
defer func() { | |
// Last one out closes shop | |
if atomic.AddInt32(&workers, -1) == 0 { | |
close(friends) | |
} | |
}() | |
for id := range friendIds { | |
if friend, err := GetUserProfile(ctx, id); err != nil { | |
return fmt.Errorf("GetUserProfile %d: %s", user, err) | |
} else { | |
select { | |
case <-ctx.Done(): | |
return ctx.Err() | |
case friends <- friend: | |
} | |
} | |
} | |
return nil | |
}) | |
} | |
// Reduce | |
ret := map[string]*User{} | |
g.Go(func() error { | |
for friend := range friends { | |
ret[friend.Name] = friend | |
} | |
return nil | |
}) | |
return ret, g.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment