Created
January 22, 2020 01:46
-
-
Save trilliwon/9a097c05ea3020068cf64f3e0b59c0f5 to your computer and use it in GitHub Desktop.
RxSwift Activity Indicator
This file contains hidden or 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
private struct ActivityToken<E>: ObservableConvertibleType, Disposable { | |
private let _source: Observable<E> | |
private let _dispose: Cancelable | |
init(source: Observable<E>, disposeAction: @escaping () -> Void) { | |
_source = source | |
_dispose = Disposables.create(with: disposeAction) | |
} | |
func dispose() { | |
_dispose.dispose() | |
} | |
func asObservable() -> Observable<E> { | |
return _source | |
} | |
} | |
import RxCocoa | |
/** | |
Enables monitoring of sequence computation. | |
If there is at least one sequence computation in progress, `true` will be sent. | |
When all activities complete `false` will be sent. | |
*/ | |
public class ActivityIndicator: SharedSequenceConvertibleType { | |
public typealias Element = Bool | |
public typealias SharingStrategy = DriverSharingStrategy | |
private let _lock = NSRecursiveLock() | |
private let _relay = BehaviorRelay(value: 0) | |
private let _loading: SharedSequence<SharingStrategy, Bool> | |
public init() { | |
_loading = _relay.asDriver() | |
.map { $0 > 0 } | |
.distinctUntilChanged() | |
} | |
fileprivate func trackActivityOfObservable<Source: ObservableConvertibleType>(_ source: Source) -> Observable<Source.Element> { | |
return Observable.using({ () -> ActivityToken<Source.Element> in | |
self.increment() | |
return ActivityToken(source: source.asObservable(), disposeAction: self.decrement) | |
}) { t in | |
return t.asObservable() | |
} | |
} | |
private func increment() { | |
_lock.lock() | |
_relay.accept(_relay.value + 1) | |
_lock.unlock() | |
} | |
private func decrement() { | |
_lock.lock() | |
_relay.accept(_relay.value - 1) | |
_lock.unlock() | |
} | |
public func asSharedSequence() -> SharedSequence<SharingStrategy, Element> { | |
return _loading | |
} | |
} | |
extension ObservableConvertibleType { | |
public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<Element> { | |
return activityIndicator.trackActivityOfObservable(self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment