How to receive from channel till it has values in GO

Issue

A function has loop which call a go routine inside it with a channel passed into it.
After this, I try receiving from channel till it has values.

The go function passes value in channel upon each call.

My channel runs infinitely.

func (m *StreamsDAO) FindOutput(input model.Input) ([]model.Output, error) {

// SOME CODE

var chanNumber int = (input.EndTime - input.StartTime)/60
outputChan := make(chan model.Output, chanNumber)
for i := input.StartTime; i < input.EndTime ;i = i+(slider*60) {

// SOME CODE

    go ForEachSlide(i, outputChan)
    for outputC := range outputChan {
        outputs = append(outputs, outputC)
    }
}
return outputs, err

}

func ForEachSlide(i int, outputChan chan model.Output) {

// SOME CODE

outputChan <- output
//  close(outputChan)

}

Its looping infinite as there in no stop for receiving from channel.
If close channel is used, only single element is received from channel thats as expected, but I need all values from the channel.

Solution

Finally got the answer using WaitGroup. Sharing link for complete reference:
https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/

Answered By – hellokuldeep

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.