refactor dynTotal example
Vladimir Bauer
4 years ago
| 15 | 15 | func main() { |
| 16 | 16 | p := mpb.New(mpb.WithWidth(64)) |
| 17 | 17 | |
| 18 | var total int64 | |
| 19 | 18 | // new bar with 'trigger complete event' disabled, because total is zero |
| 20 | bar := p.AddBar(total, | |
| 19 | bar := p.AddBar(0, | |
| 21 | 20 | mpb.PrependDecorators(decor.Counters(decor.UnitKiB, "% .1f / % .1f")), |
| 22 | 21 | mpb.AppendDecorators(decor.Percentage()), |
| 23 | 22 | ) |
| 26 | 25 | read := makeStream(200) |
| 27 | 26 | for { |
| 28 | 27 | n, err := read() |
| 29 | total += int64(n) | |
| 30 | 28 | if err == io.EOF { |
| 29 | // triggering complete event now | |
| 30 | bar.SetTotal(-1, true) | |
| 31 | 31 | break |
| 32 | 32 | } |
| 33 | // while total is unknown, | |
| 34 | // set it to a positive number which is greater than current total, | |
| 35 | // to make sure no complete event is triggered by next IncrBy call. | |
| 36 | bar.SetTotal(total+2048, false) | |
| 33 | // increment methods won't trigger complete event because bar was constructed with total = 0 | |
| 37 | 34 | bar.IncrBy(n) |
| 35 | // following call is not required, it's called to show some progress instead of an empty bar | |
| 36 | bar.SetTotal(bar.Current()+2048, false) | |
| 38 | 37 | time.Sleep(time.Duration(rand.Intn(10)+1) * maxSleep / 10) |
| 39 | 38 | } |
| 40 | ||
| 41 | // force bar complete event, note true flag | |
| 42 | bar.SetTotal(total, true) | |
| 43 | 39 | |
| 44 | 40 | p.Wait() |
| 45 | 41 | } |