f5/async_task.go
aozhiwei b6f20e6837 1
2023-12-12 11:07:05 +08:00

77 lines
1.3 KiB
Go

package f5
type AsyncTask struct {
status int32
cb func(*AsyncTask)
succCb func(*AsyncTask)
failCb func(*AsyncTask)
execTimes int64
}
func (this *AsyncTask) init(cb func(*AsyncTask)) *AsyncTask {
this.cb = cb
return this
}
func (this *AsyncTask) GetExecTimes() int64 {
return this.execTimes
}
func (this *AsyncTask) IsRunning() bool {
return this.status == 0
}
func (this *AsyncTask) IsSucc() bool {
return this.status > 0
}
func (this *AsyncTask) IsFail() bool {
return this.status < 0
}
func (this *AsyncTask) SetSucc() {
if !this.IsRunning() {
panic("task is not runing")
}
this.status = 1
if this.succCb != nil {
this.succCb(this)
}
}
func (this *AsyncTask) SetFail() {
if !this.IsRunning() {
panic("task is not runing")
}
this.status = -1
if this.failCb != nil {
this.failCb(this)
}
}
func (this *AsyncTask) Continue() *AsyncTask {
if !this.IsRunning() {
panic("task is not runing")
}
GetApp().RegisterMainThreadCb(
func () {
this.cb(this)
this.execTimes += 1
})
return this
}
func (this *AsyncTask) OnSucc(cb func(*AsyncTask)) *AsyncTask {
this.succCb = cb
return this
}
func (this *AsyncTask) OnFail(cb func(*AsyncTask)) *AsyncTask {
this.failCb = cb
return this
}
func NewAsyncTask(cb func(*AsyncTask)) *AsyncTask {
return new(AsyncTask).init(cb).Continue()
}