class ChainObjc: NSObject {
public typealias NextBlock = (_ result: Bool) -> Void
fileprivate var next: NextBlock?
fileprivate var nextObj: ChainObjc?
fileprivate var tempBlock: ((_ :NextBlock?) -> ())?
fileprivate var hasNext: Bool = false
fileprivate var tempObj: ChainObjc?
@discardableResult
func handle(_ isNow: Bool = false,completBlock:((_ :NextBlock?) -> ())?) -> ChainObjc {
tempObj = self//通過循環(huán)引用,減少外部的強引用操作
tempBlock = completBlock
self.next = {[weak self](hasNext) in
if hasNext {
if self?.nextObj?.tempBlock == nil {
self?.nextObj?.hasNext = true
}
self?.nextObj?.tempBlock?(self?.nextObj?.next)
}
self?.tempObj = nil
}
let temp = ChainObjc()
self.nextObj = temp
defer {
if isNow || hasNext {
tempBlock?(next)
}
}
return temp
}
deinit {
print("---------dealloc")
}
}
//調(diào)用api
ChainObjc().handle(true ,completBlock: { (nextBlock) in
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
print("---------1")
nextBlock?(true)
}
}).handle(completBlock: { (nextBlock) in
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
print("---------2")
nextBlock?(true)
}
}).handle(completBlock: { (nextBlock) in
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
print("---------3")
nextBlock?(true)
}
})
總結(jié):RXSwift和RAC核心就是block套block,感覺沒必要寫那么復(fù)雜,面向Api開發(fā),只要實現(xiàn)這種責(zé)任鏈的條用就夠了,對于一些其他的需求,比如說是否忽略中間next,直接調(diào)用成功或者失敗,等,可以自己擴展