Skip to content

Commit

Permalink
feat:ctx fork
Browse files Browse the repository at this point in the history
  • Loading branch information
wuqinqiang committed Mar 13, 2022
1 parent a313d9e commit e8f5e57
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@

# Dependency directories (remove the comment below to include it)
# vendor/

.idea/
14 changes: 14 additions & 0 deletions event_entity.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package easyfsm

import "context"

type (
// EventEntity is the core that wraps the basic Event methods.
EventEntity struct {
hook EventHook
eventName EventName
observers []EventObserver
eventFunc EventFunc
// issue:https://github.com/wuqinqiang/easyfsm/issues/16
forkCtxFunc func(ctx context.Context) context.Context
}

EventEntityOpt func(entity *EventEntity)
Expand Down Expand Up @@ -34,6 +38,9 @@ func NewEventEntity(event EventName, handler EventFunc,
eventName: event,
eventFunc: handler,
observers: make([]EventObserver, 0),
forkCtxFunc: func(ctx context.Context) context.Context {
return context.Background()
},
}
for _, opt := range opts {
opt(entity)
Expand Down Expand Up @@ -61,6 +68,12 @@ func WithHook(hook EventHook) EventEntityOpt {
}
}

func WithForkCtxFunc(fn func(ctx context.Context) context.Context) EventEntityOpt {
return func(entity *EventEntity) {
entity.forkCtxFunc = fn
}
}

// Execute executes the event.
func (e *EventEntity) Execute(param *Param) (State, error) {
if e.hook != nil {
Expand All @@ -78,6 +91,7 @@ func (e *EventEntity) Execute(param *Param) (State, error) {

// Asynchronous notify observers
GoSafe(func() {
param.Ctx = e.forkCtxFunc(param.Ctx)
e.notify(param)
})
return state, nil
Expand Down
9 changes: 8 additions & 1 deletion helper.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package easyfsm

import "github.com/wuqinqiang/easyfsm/log"
import (
"context"
"github.com/wuqinqiang/easyfsm/log"
)

func GoSafe(fn func()) {
go goSafe(fn)
Expand All @@ -14,3 +17,7 @@ func goSafe(fn func()) {
}()
fn()
}

type ForkCtxInterface interface {
ForkCtx(ctx context.Context) context.Context
}

0 comments on commit e8f5e57

Please sign in to comment.