Initially, I created a class called BaseObserver in Swift. In the subscribe method, I pass this class. Now, I am attempting to achieve the same functionality in RxJS using TypeScript.
This approach proves useful when you need to execute actions both before and after certain events.
import Foundation
import RxSwift
class BaseObserver<Element>: ObserverType {
public typealias E = Element
var beforeClosure: (() -> Void)?
var completeClosure: ((E) -> Void)?
var errorClosure: ((Error) -> Void)?
var completedClosure: (() -> Void)?
var alwaysClosure: (()->())?
var onCompleteOrError: ((Error?) -> Void)?
init(beforeComplete: (() -> Void)? = nil, onComplete: ((E) -> Void)? = nil, onError: ((Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, always: (()->())? = nil, onCompleteOrError: ((Error?) -> Void)? = nil) {
self.alwaysClosure = always
self.completeClosure = onComplete
self.errorClosure = onError
self.completedClosure = onCompleted
self.beforeClosure = beforeComplete
self.onCompleteOrError = onCompleteOrError
}
func on(_ event: Event<Element>) {
switch event {
case .next(let element):
beforeClosure?()
completeClosure?(element)
case .error(let error):
beforeClosure?()
errorClosure?(error)
onCompleteOrError?(error)
case .completed:
completedClosure?()
onCompleteOrError?(nil)
}
alwaysClosure?()
}
}