IOS – 模擬RxSwift

class DisposeBag {
var delegate: RxSimulator?
deinit {
print("test11 DisposeBag deinit")
delegate = nil
}
}
class RxSimulator {
var action: ((Bool) -> Void)? = nil
weak var disposeBag: DisposeBag?
func createObservable(closure: ((Bool) -> Void)? = nil) -> RxSimulator {
action = closure
return self
}
func subscribe(callback: ((Bool) -> Void)? = nil) -> RxSimulator {
action = callback
return self
}
func onNext(val: Bool) {
action?(val)
}
func disposed(by disposeBag: DisposeBag) {
self.disposeBag = disposeBag
self.disposeBag?.delegate = self
}
deinit {
print("test11 RxSimulator deinit")
}
}
class ViewController: UIViewController {
var disposeBag: DisposeBag? = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
if let disposeBag = disposeBag {
let myClosure: ((Bool) -> Void)? = { input in
print("execute myClosure")
}
let observable = RxSimulator().createObservable(closure: myClosure)
observable.subscribe { result in
print("test11 In subscribe, result is: \(result)")
}.disposed(by: disposeBag)
DispatchQueue.global().asyncAfter(deadline: .now() + 3) {
print("test11 execute observable.onNext")
observable.onNext(val: true)
}
DispatchQueue.global().asyncAfter(deadline: .now() + 5) {
self.disposeBag = nil
}
}
}
}