美文网首页
最简单的仿RXSwift小工具

最简单的仿RXSwift小工具

作者: 不拘小节123456 | 来源:发表于2021-05-26 10:55 被阅读0次
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//通过循环引用,减少外部的强引用操作
        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")
    }
}


//调用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)
            }
        })

总结:RXSwift和RAC核心就是block套block,感觉没必要写那么复杂,面向Api开发,只要实现这种责任链的条用就够了,对于一些其他的需求,比如说是否忽略中间next,直接调用成功或者失败,等,可以自己扩展

相关文章

网友评论

      本文标题:最简单的仿RXSwift小工具

      本文链接:https://www.haomeiwen.com/subject/ovqksltx.html