Skip to content

Instantly share code, notes, and snippets.

@Odrakir
Created November 25, 2016 14:57
Show Gist options
  • Save Odrakir/c95819f2162076f2fb45a366f704028b to your computer and use it in GitHub Desktop.
Save Odrakir/c95819f2162076f2fb45a366f704028b to your computer and use it in GitHub Desktop.
RxMiddleware for Cachopo (A ReSwift wrapper with RxSwift)
import Foundation
import RxSwift
import ReSwift
class RxMiddleware<State:StateType, Environment:EnvironmentType>
{
let context:ContextType<State, Environment>
var disposeBag = DisposeBag()
init(context:ContextType<State, Environment>) {
self.context = context
}
func middleware() -> Middleware
{
return { dispatch, getState in
return { next in
return { action in
guard let rxaction = action as? RxStore<State, Environment>.RxAction else {
next(action)
return Observable<Action>.empty()
}
let subject = PublishSubject<Action>()
rxaction.run(self.context)
.subscribe(
onNext: { action in
next(action)
subject.onNext(action)
},
onError: { error in
next(ErrorAction(error: error))
subject.onError(error)
},
onCompleted: {
subject.onCompleted()
})
.addDisposableTo(self.disposeBag)
return subject
.observeOn(MainScheduler.instance)
.asObservable()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment