Skip to content

Instantly share code, notes, and snippets.

@lokshunhung
Created May 9, 2023 04:09
Show Gist options
  • Select an option

  • Save lokshunhung/ab59d15eea257bca306b75a5af09c6c1 to your computer and use it in GitHub Desktop.

Select an option

Save lokshunhung/ab59d15eea257bca306b75a5af09c6c1 to your computer and use it in GitHub Desktop.
import Combine
import RxSwift
public final class RxCurrentValueSubject<Output, Failure: Error>: Combine.Subject {
private let rxSubject: RxSwift.BehaviorSubject<Output>
private let combineSubject: Combine.CurrentValueSubject<Output, Failure>
private let disposeBag = RxSwift.DisposeBag()
public init(rxSubject: RxSwift.BehaviorSubject<Output>) {
self.rxSubject = rxSubject
// swiftlint:disable:next force_try
self.combineSubject = Combine.CurrentValueSubject(try! rxSubject.value())
self.rxSubject
.subscribe(onNext: { [weak self] next in
self?.combineSubject.send(next)
}, onError: { [weak self] error in
guard let error = error as? Failure else { return }
self?.combineSubject.send(completion: .failure(error))
}, onCompleted: { [weak self] in
self?.combineSubject.send(completion: .finished)
})
.disposed(by: disposeBag)
}
public func receive<S: Combine.Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Failure {
combineSubject.receive(subscriber: subscriber)
}
public func send(_ value: Output) {
rxSubject.onNext(value)
}
public func send(completion: Combine.Subscribers.Completion<Failure>) {
switch completion {
case .finished: rxSubject.onCompleted()
case .failure(let error): rxSubject.onError(error)
}
}
public func send(subscription: Combine.Subscription) {
combineSubject.send(subscription: subscription)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment