summaryrefslogtreecommitdiff
path: root/go/src/lib/statusline/async.go
blob: 32c9a2b780df03505eb0e62f14ad32e496f8f348 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package statusline

import (
	"io"
	"time"
)

type AsyncStatusLine struct {
	lines chan string
	end   chan struct{}
}

func NewAsyncStatusLine(out io.Writer, d time.Duration) *AsyncStatusLine {
	ret := &AsyncStatusLine{
		lines: make(chan string),
		end:   make(chan struct{}),
	}
	go func() {
		sl := NewStatusLine(out)
		ticker := time.NewTicker(d)
		var line string
		for {
			select {
			case <-ticker.C:
				sl.Put(line)
			case l := <-ret.lines:
				line = l
			case <-ret.end:
				sl.End()
				ticker.Stop()
			}
		}
	}()
	return ret
}

func (sl *AsyncStatusLine) Put(line string) {
	sl.lines <- line
}

func (sl *AsyncStatusLine) End() {
	sl.end <- struct{}{}
	close(sl.lines)
	close(sl.end)
}