Skip to content

Instantly share code, notes, and snippets.

@MartinMoizard
Created June 8, 2018 16:29
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save MartinMoizard/c39e8d84b58fda5e7e845ca3eec385ac to your computer and use it in GitHub Desktop.
Save MartinMoizard/c39e8d84b58fda5e7e845ca3eec385ac to your computer and use it in GitHub Desktop.
import Foundation
import RxSwift
public protocol LoadingDataConvertible {
/// Type of element in event
associatedtype ElementType
/// Event representation of this instance
var data: Event<ElementType>? { get }
var loading: Bool { get }
}
public struct LoadingResult<E>: LoadingDataConvertible {
public let data: Event<E>?
public let loading: Bool
public init(_ loading: Bool) {
self.data = nil
self.loading = loading
}
public init(_ data: Event<E>) {
self.data = data
self.loading = false
}
}
extension ObservableType {
public func monitorLoading() -> Observable<LoadingResult<E>> {
return self.materialize()
.map(LoadingResult.init)
.startWith(LoadingResult(true))
}
}
extension ObservableType where E: LoadingDataConvertible {
public func loading() -> Observable<Bool> {
return self
.map { $0.loading }
}
public func data() -> Observable<E.ElementType> {
return self
.events()
.elements()
}
public func errors() -> Observable<Error> {
return self
.events()
.errors()
}
// MARK: - Private
private func events() -> Observable<Event<E.ElementType>> {
return self
.filter { !$0.loading }
.map { $0.data }
.unwrap()
}
}
@JoeySlomowitz
Copy link

I'm getting a couple of errors with this implementation. Is that because this is from an older version of Rx?
Errors appear on lines with .errors() as well as .elements()

@AngeloGiurano
Copy link

@JoeySlomowitz you need RxSwiftExt for that

@Andy0570
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment