go-observer icon indicating copy to clipboard operation
go-observer copied to clipboard

The way to stop observers periodically

Open Antonboom opened this issue 3 years ago • 0 comments

Hello. Thanks for the interesting library!

We were faced with the need for a mechanism for stopping observers without stopping the property:

package main

import (
	"fmt"
	"math/rand"
	"time"

	"github.com/imkira/go-observer"
)

type stop struct{}

func main() {
	obs := observer.NewProperty(0)

	go func() {
		t := time.Tick(time.Second * 3)

		for {
			select {
			case <-t:
				obs.Update(stop{}) // obs.Interrupt()
			default:
				obs.Update(rand.Int())
			}
			time.Sleep(time.Second)
		}
	}()

	stream := obs.Observe()
	for {
		<-stream.Changes()
		switch i := stream.Next().(type) {
		case stop:
			fmt.Println("exit")
		case int:
			fmt.Println(i)
		}
		/*
			select {
			case <-stream.Changes():
			case <-stream.Interrupts():
			}
		*/
	}
}

In the comments I suggested a new possible observer API. What do you think about that?

Antonboom avatar Nov 19 '20 08:11 Antonboom