listener

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2022 License: MIT Imports: 4 Imported by: 0

README

go-slice-struct-listener

A Go library to listen slice of struct (when feed new data then output show id was added , id was updated or id was deleted)


Usage

package main

import (
	"fmt"

	listener "github.com/panapol-p/go-slice-struct-listener"
)

type FeedData struct {
	ID    string `listener:"id"`
	Name  string
	Score float32
}

func main() {
	fs := []FeedData{
		{ID: "1", Name: "Bob", Score: 98.50},
		{ID: "2", Name: "Joe", Score: 92.50},
	}

	l := listener.NewListener[FeedData]()

	// set callback func if you need
	f := func(e []listener.Events[FeedData]) {
		fmt.Println("[callback func]", "receive new event!!", e)
	}
	l.SetCallback(f)

	events := l.AddNewValue(fs)
	fmt.Println(events) // [{1 added {1 Bob 98.5}} {2 added {2 Joe 92.5}}]

	fs = []FeedData{
		{ID: "1", Name: "Bob", Score: 96.50},
		{ID: "2", Name: "Joe", Score: 92.50},
		{ID: "3", Name: "Micky", Score: 89.70},
	}
	events = l.AddNewValue(fs)
	fmt.Println(events) // [{1 updated {1 Bob 96.5}} {3 added {3 Micky 89.7}}]

	fs = []FeedData{
		{ID: "1", Name: "Bob", Score: 96.50},
	}
	events = l.AddNewValue(fs)
	fmt.Println(events) // [{2 deleted {  0}} {3 deleted {  0}}]
}

License

Distributed under the MIT License. See license for more information.

Contributing

Contributions are welcome! Feel free to check our open issues.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DataStruct

type DataStruct interface{}

type EventState

type EventState string
var EventStateAdded EventState = "added"
var EventStateDeleted EventState = "deleted"
var EventStateUpdated EventState = "updated"

type Events

type Events[T any] struct {
	ID    string
	State EventState
	Data  T
}

type Listener

type Listener[T any] struct {
	CurrentValue  map[string]Value[T]
	NewValue      map[string]Value[T]
	EventCallback func([]Events[T])
	CurrentEvent  []Events[T]
	// contains filtered or unexported fields
}

func NewListener

func NewListener[T any]() *Listener[T]

func (*Listener[T]) AddNewValue

func (l *Listener[T]) AddNewValue(a []T) []Events[T]

func (*Listener[T]) SetCallback

func (l *Listener[T]) SetCallback(f func([]Events[T]))

type Value

type Value[T any] struct {
	Hash string
	Data T
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL