我正在尝试定期(每 10 秒)调用一个返回模型 Json 对象的 API:
struct MyModel {
var messagesCount: Int?
var likesCount: Int?
}
如果值更改messageCount
,则更新 UI。likesCount
我尝试了 Timer 解决方案,但我发现它有点乱,我想要一个使用 RxSwift 和 RxAlamofire 的更清洁的解决方案。
非常感谢任何帮助,因为我是 Rx 的新手。
我正在尝试定期(每 10 秒)调用一个返回模型 Json 对象的 API:
struct MyModel {
var messagesCount: Int?
var likesCount: Int?
}
如果值更改messageCount
,则更新 UI。likesCount
我尝试了 Timer 解决方案,但我发现它有点乱,我想要一个使用 RxSwift 和 RxAlamofire 的更清洁的解决方案。
非常感谢任何帮助,因为我是 Rx 的新手。
欢迎来到 StackOverflow!
这需要相当多的运算符,我建议在ReactiveX 运算符页面上查找它们,每次我忘记某些东西时都会检查它们。
首先,确保MyModel
符合,Decodable
以便可以从 JSON 响应构造它(请参阅Codable)。
let willEnterForegroundNotification = NotificationCenter.default.rx.notification(.UIApplicationWillEnterForeground)
let didEnterBackgroundNotification = NotificationCenter.default.rx.notification(.UIApplicationDidEnterBackground)
let myModelObservable = BehaviorRelay<MyModel?>(value: nil)
willEnterForegroundNotification
// discard the notification object
.map { _ in () }
// emit an initial element to trigger the timer immediately upon subscription
.startWith(())
.flatMap { _ in
// create an interval timer which stops emitting when the app goes to the background
return Observable<Int>.interval(10, scheduler: MainScheduler.instance)
.takeUntil(didEnterBackgroundNotification)
}
.flatMapLatest { _ in
return RxAlamofire.requestData(.get, yourUrl)
// get Data object from emitted tuple
.map { $0.1 }
// ignore any network errors, otherwise the entire subscription is disposed
.catchError { _ in .empty() }
}
// leverage Codable to turn Data into MyModel
.map { try? JSONDecoder().decode(MyModel.self, from: $0) } }
// operator from RxOptional to turn MyModel? into MyModel
.filterNil()
.bind(to: myModelObservable)
.disposed(by: disposeBag)
然后,您可以继续将数据流传输到您的 UI 元素中。
myModelObservable
.map { $0.messagesCount }
.map { "\($0) messages" }
.bind(to: yourLabel.rx.text }
.disposed(by: disposeBag)
我没有运行此代码,因此此处可能存在一些拼写错误/缺少转换,但这应该为您指明正确的方向。随时要求澄清。如果对 Rx真的很陌生,我建议您阅读入门指南。这很棒!Rx 很强大,但是我花了一段时间才掌握。
正如@daniel-t 指出的那样,使用Observable<Int>.interval
.
CloakedEddy 的回答非常接近,值得点赞。然而,他使它变得比必要的复杂一些。Interval 在内部使用 DispatchSourceTimer,当应用程序进入后台并返回前台时,它将自动停止并重新启动。他在记住捕捉错误以阻止流展开方面也做得很好。
我假设下面的代码在 AppDelegate 或高级协调器中。此外,myModelSubject
是一个ReplaySubject<MyModel>
(create it with:ReplaySubject<MyModel>.create(bufferSize: 1)
应该放置在视图控制器可以访问或传递给视图控制器的地方。
Observable<Int>.interval(10, scheduler: MainScheduler.instance) // fire at 10 second intervals.
.flatMapLatest { _ in
RxAlamofire.requestData(.get, yourUrl) // get data from the server.
.catchError { _ in .empty() } // don't let error escape.
}
.map { $0.1 } // this assumes that alamofire returns `(URLResponse, Data)`. All we want is the data.
.map { try? JSONDecoder().decode(MyModel.self, from: $0) } // this assumes that MyModel is Decodable
.filter { $0 != nil } // filter out nil values
.map { $0! } // now that we know it's not nil, unwrap it.
.bind(to: myModelSubject) // store the value in a global subject that view controllers can subscribe to.
.disposed(by: bag) // always clean up after yourself.