Skip to content

Commit 3674fd1

Browse files
committed
more realistic dyn total example
1 parent 42963cd commit 3674fd1

File tree

4 files changed

+31
-31
lines changed

4 files changed

+31
-31
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ _Note:_ it is preferable to go get from github.com, rather than gopkg.in. See is
106106

107107
#### [Dynamic total](examples/dynTotal/main.go)
108108

109-
![dynamic total](examples/gifs/OaBiIexGNgHLVGQLlieZf6x1x.svg)
109+
![dynamic total](examples/gifs/godEMrCZmJkHYH1X9dN4Nm0U7.svg)
110110

111111
#### [Complex example](examples/complex/main.go)
112112

examples/dynTotal/main.go

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"io"
45
"math/rand"
56
"time"
67

@@ -15,40 +16,39 @@ func init() {
1516
func main() {
1617
p := mpb.New(mpb.WithWidth(64))
1718

18-
// initialize bar with dynamic total and initial total guess = 80
19-
bar := p.AddBar(80,
20-
// indicate that total is dynamic, could be omitted if total set to 0
21-
mpb.BarDynamicTotal(),
22-
// trigger total auto increment by 1, when 18 % remains till bar completion
23-
mpb.BarAutoIncrTotal(18, 1),
24-
mpb.PrependDecorators(decor.CountersNoUnit("%d / %d")),
19+
bar := p.AddBar(0, // by setting total to 0, we indicate that it's dynamic
20+
mpb.PrependDecorators(decor.Counters(decor.UnitKiB, "% .1f / % .1f")),
2521
mpb.AppendDecorators(decor.Percentage()),
2622
)
2723

28-
totalUpd := make(chan int64)
29-
go func() {
30-
for {
31-
total, ok := <-totalUpd
32-
bar.SetTotal(total, !ok)
33-
if !ok {
34-
break
35-
}
24+
var written int64
25+
maxSleep := 100 * time.Millisecond
26+
read := makeStream(200)
27+
for {
28+
n, err := read()
29+
written += int64(n)
30+
time.Sleep(time.Duration(rand.Intn(10)+1) * maxSleep / 10)
31+
bar.IncrBy(n)
32+
if err == io.EOF {
33+
break
3634
}
37-
}()
38-
39-
max := 100 * time.Millisecond
40-
for i := 0; !bar.Completed(); i++ {
41-
if i == 140 {
42-
totalUpd <- 190
43-
}
44-
if i == 250 {
45-
totalUpd <- 300
46-
// final upd, so closing channel
47-
close(totalUpd)
48-
}
49-
time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
50-
bar.Increment()
35+
bar.SetTotal(written+1024, false)
5136
}
5237

38+
// final set total, final=true
39+
bar.SetTotal(written, true)
40+
// need to increment once, to shutdown the bar
41+
bar.IncrBy(0)
42+
5343
p.Wait()
5444
}
45+
46+
func makeStream(limit int) func() (int, error) {
47+
return func() (int, error) {
48+
if limit <= 0 {
49+
return 0, io.EOF
50+
}
51+
limit--
52+
return rand.Intn(1024) + 1, nil
53+
}
54+
}

examples/gifs/OaBiIexGNgHLVGQLlieZf6x1x.svg

Lines changed: 0 additions & 1 deletion
This file was deleted.

examples/gifs/godEMrCZmJkHYH1X9dN4Nm0U7.svg

Lines changed: 1 addition & 0 deletions
Loading

0 commit comments

Comments
 (0)