您可以使用来自RxSwift repo的ActivityIndi cator 。我在我的项目中使用MBProgressHUD。首先,您需要为此库创建扩展:
extension MBProgressHUD {
/**
Bindable sink for MBProgressHUD show/hide methods.
*/
public var rx_mbprogresshud_animating: AnyObserver<Bool> {
return AnyObserver { event in
MainScheduler.ensureExecutingOnScheduler()
switch (event) {
case .Next(let value):
if value {
let loadingNotification = MBProgressHUD.showHUDAddedTo(UIApplication.sharedApplication().keyWindow?.subviews.last, animated: true)
loadingNotification.mode = self.mode
loadingNotification.labelText = self.labelText
loadingNotification.dimBackground = self.dimBackground
} else {
MBProgressHUD.hideHUDForView(UIApplication.sharedApplication().keyWindow?.subviews.last, animated: true)
}
case .Error(let error):
let error = "Binding error to UI: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
case .Completed:
break
}
}
}
}
import RxSwift
import RxCocoa
extension Reactive where Base: MBProgressHUD {
public var animation: Binder<Bool> {
return Binder(self.base) { hud, show in
guard let view = UIApplication.shared.keyWindow?.subviews.last()! else { return }
if show {
if hud.superview == nil {
view.addSubview(hud)
}
hud.show(animated: true)
} else {
hud.hide(animated: true)
}
}
}
}
接下来,您需要在 ViewController 类中创建 ActivityIndicator 对象:
let progress = MBProgressHUD()
progress.mode = MBProgressHUDMode.Indeterminate
progress.labelText = "Loading..."
progress.dimBackground = true
let indicator = ActivityIndicator()
indicator.asObservable()
.bindTo(progress.rx_mbprogresshud_animating)
.addDisposableTo(bag)
接下来只需在您的序列中使用 trackActivity() 函数:
apiMethod
.trackActivity(indicator)
.subscribeNext { stringArray in
items.value = stringArray
}
.addDisposableTo(bag)