Created
June 8, 2018 16:29
-
-
Save MartinMoizard/c39e8d84b58fda5e7e845ca3eec385ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 you need RxSwiftExt for that
Might be a better solution: https://github.com/ReactiveX/RxSwift/blob/main/RxExample/RxExample/Services/ActivityIndicator.swift
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()