DefferedTaskKit is a simple library for wrapping closures that can be executed at a later time.
DefferedTask works with Value, but DefferedResult is working with Result type.
Important
- Task will be executed only on subscription by 'onComplete' method'. If you don't subscribe to the task, it will never be executed.
- By default, the task is 'selfRetaint' and you don't need save reference in variables for task. Use 'weakify()' method to prevent retain cycle.
- You can handle 'deinit' of task if you need.
DefferedTask<Int>{ completion inprint("start task")DispatchQueue.main.asyncAfter(deadline:.now()+1){completion(10)print("end task")}} onDeinit:{print("onDeinit")}.beforeComplete{ result inprint("beforeComplete: \(result)") // print 10
}.afterComplete{ result inprint("afterComplete: \(result)") // print 10
}.set(userInfo:"subject").strongify().map{ value inreturn value *2}.beforeComplete{ result inprint("beforeComplete: \(result)") // print 20
}.afterComplete{ result inprint("afterComplete: \(result)") // print 20
}.onComplete{ result inprint("onComplete: \(result)") // print 20
}console output:
start task
beforeComplete: 10
beforeComplete: 20
onComplete: 20
afterComplete: 20
afterComplete: 10
onDeinit
end task
Special task that is caching tasks while executing single main task.
letpending:PendingTask<Int>=.init()foriin0..<10{
pending.current{ completion inprint("start main task")DispatchQueue.main.asyncAfter(deadline:.now()+1){completion(10)print("end main task")}}.onComplete{ _ inprint("onComplete: \(i)")}}console output:
start main task
onComplete: 0
onComplete: 1
onComplete: 2
onComplete: 3
onComplete: 4
onComplete: 5
onComplete: 6
onComplete: 7
onComplete: 8
onComplete: 9
end main task
Special task that is polling main task with idleTimeInterval and retryCount.
varidx=0PollingTask<Int>(idleTimeInterval:1,
retryCount:5,
generator:{return.init { completion inprint("start main task")DispatchQueue.main.asyncAfter(deadline:.now()+1){completion(idx)
idx +=1print("end main task")}}},
shouldRepeat:{ idx inprint("shouldRepeat \(idx)")return idx <4},
response:{ idx inprint("response: \(idx)")}).start().onComplete{ result inprint("completed \(result)")}console output:
start main task
response: 0
shouldRepeat 0
end main task
start main task
response: 1
shouldRepeat 1
end main task
start main task
response: 2
shouldRepeat 2
end main task
start main task
response: 3
shouldRepeat 3
end main task
start main task
response: 4
shouldRepeat 4
completed 4
end main task