Rework subscriptions, allowing for them to be easily managed by the developer
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Christian Rocha · committed by Christian Rocha · parent f64f86f · Browse files · 1 file·+114 added−22 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+114 added−22 removed
- other:+114 added−22 removed
Provenance
- Commit
444c36b- Tree
c8f77f9- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
f64f86f
1 file changed+114 added−22 removed
modified:tea.go+114 added-22 removed
14 unmodified lines15 16 // Cmd is an IO operation. If it's nil it's considered a no-op.17 type Cmd func(Model) Msg18 19-// Sub is an event subscription. If it returns nil it's considered a no-op.19+// Sub is an event subscription. If it returns nil it's considered a no-op,20+// but there's really no reason to have a nil subscription.21 type Sub func(Model) Msg22 23+// Subs is a keyed set of subscriptions. The key should be a unique24+// identifier; two different subscriptions should not have the same key25+type Subs map[string]Sub26+27+// Subscriptions returns a map of subscriptions (Subs) our application will28+// subscribe to. If Subscriptions is nil it's considered a no-op.29+type Subscriptions func(Model) Subs30+31+// subscription is an internal reference to a subscription used in subscription32+// management.33+type subscription struct {34+ done chan struct{}35+ sub Sub36+}37+38+// subManager is used to manage active subscriptions, hence the pointers.39+type subManager map[string]*subscription40+41+// endAll stops all subscriptions and remove subscription references from42+// subManager.43+func (m *subManager) endAll() {44+ if m != nil {45+ for key, sub := range *m {46+ close(sub.done)47+ delete(*m, key)48+ }49+ }50+}51+52 // Init is the first function that will be called. It returns your initial53 // model and runs an optional command54 type Init func() (Model, Cmd)55 8 unmodified lines64 type Program struct {65 init Init66 update Update67 view View38- subscriptions []Sub68+ subscriptions Subscriptions69+ model Model70 }71 72 // ErrMsg is just a regular message containing an error. We handle it in Update73 // just like a regular message by case switching. Of course, the developer25 unmodified lines99 // Signals that the program should quit100 type quitMsg struct{}101 102 // NewProgram creates a new Program72-func NewProgram(init Init, update Update, view View, subs []Sub) *Program {103+func NewProgram(init Init, update Update, view View, subs Subscriptions) *Program {104 return &Program{105 init: init,106 update: update,107 view: view,3 unmodified lines111 112 // Start initializes the program113 func (p *Program) Start() error {114 var (84- model Model115 cmd Cmd116+ subs = make(subManager)117 cmds = make(chan Cmd)118 msgs = make(chan Msg)119 done = make(chan struct{})120 linesRendered int5 unmodified lines126 }127 defer restoreTerminal()128 129 // Initialize program99- model, cmd = p.init()130+ p.model, cmd = p.init()131 if cmd != nil {132 go func() {133 cmds <- cmd134 }()135 }136 137 // Render initial view107- linesRendered = p.render(model, linesRendered)138+ linesRendered = p.render(p.model, linesRendered)139 140 // Subscribe to user input. We could move this out of here and offer it141 // as a subscription, but it blocks nicely and seems to be a common enough142 // need that we're enabling it by default.3 unmodified lines146 msgs <- KeyMsg(msg)147 }148 }()149 119- // Process subscriptions120- go func() {121- if len(p.subscriptions) > 0 {122- for _, sub := range p.subscriptions {123- go func(s Sub) {124- for {125- msgs <- s(model)126- }127- }(sub)128- }129- }130- }()150+ // Initialize subscriptions151+ subs = p.processSubs(msgs, subs)152 153 // Process commands154 go func() {155 for {2 unmodified lines158 return159 case cmd := <-cmds:160 if cmd != nil {161 go func() {141- msgs <- cmd(model)162+ msgs <- cmd(p.model)163 }()164 }165 }166 }7 unmodified lines174 close(done)175 return nil176 }177 157- model, cmd = p.update(msg, model)158- cmds <- cmd // process command (if any)159- linesRendered = p.render(model, linesRendered)178+ p.model, cmd = p.update(msg, p.model) // run update179+ cmds <- cmd // process command (if any)180+ subs = p.processSubs(msgs, subs) // check for new and outdated subscriptions181+ linesRendered = p.render(p.model, linesRendered) // render to terminal182 }183 }184 }185 10 unmodified lines196 }197 io.WriteString(os.Stdout, view)198 return strings.Count(view, "\r\n")199 }200+201+// Manage subscriptions. Here we run the program's Subscription function and202+// inspect the functions it returns (a Subs map). If we notice existing203+// subscriptions have disappeared from the map we stop those subscriptions204+// by ending the Goroutines they run on. If we notice new subscriptions which205+// aren't currently running, we run them as loops in a new Goroutine.206+//207+// This function should be called on initialization and after every update.208+func (p *Program) processSubs(msgs chan Msg, activeSubs subManager) subManager {209+210+ // Nothing to do.211+ if p.subscriptions == nil && activeSubs == nil {212+ return activeSubs213+ }214+215+ // There are no subscriptions. Cancel active ones and return.216+ if p.subscriptions == nil && activeSubs != nil {217+ activeSubs.endAll()218+ return activeSubs219+ }220+221+ newSubs := p.subscriptions(p.model)222+223+ // newSubs is an empty map. Cancel any active subscriptions and return.224+ if newSubs == nil {225+ activeSubs.endAll()226+ return activeSubs227+ }228+229+ // Stop subscriptions that don't exist in the new subscription map230+ if len(activeSubs) > 0 {231+ for key, sub := range activeSubs {232+ if _, exists := newSubs[key]; !exists {233+ close(sub.done)234+ delete(activeSubs, key)235+ }236+ }237+ }238+239+ // Start new subscriptions if they don't exist in the active subscription map240+ if len(newSubs) > 0 {241+ for key, sub := range newSubs {242+ if _, exists := activeSubs[key]; !exists {243+244+ if sub == nil {245+ continue246+ }247+248+ activeSubs[key] = &subscription{249+ done: make(chan struct{}),250+ sub: sub,251+ }252+253+ go func(done chan struct{}, s Sub) {254+ for {255+ select {256+ case <-done:257+ return258+ case msgs <- s(p.model):259+ continue260+ }261+ }262+ }(activeSubs[key].done, activeSubs[key].sub)263+264+ }265+ }266+ }267+268+ return activeSubs269+}