I'm trying to periodically (every 10 seconds) call an API that returns a Json object of model :
struct MyModel {
var messagesCount: Int?
var likesCount: Int?
}
And update the UI if messageCount
or likesCount
value changes.
I tried the Timer solution but i find it a little bit messy and i want a cleaner solution with RxSwift and RxAlamofire.
Any help is highly appreciated as i'm new to Rx.
There's quite a lot of operators required for this, and I would recommend to look them up on the ReactiveX Operator page, which I check every time I forget something.
First off, ensure
MyModel
conforms toDecodable
so it can be constructed from a JSON response (see Codable).Then, you can just continue the data stream into your UI elements.
I didn't run this code, so there might be some typos/missing conversions in here, but this should point you in the right direction. Feel free to ask for clarification. If are really new to Rx, I recommend going through the Getting Started guide. It's great! Rx is very powerful, but it took me a while to grasp.
As @daniel-t pointed out, the background/foreground bookkeeping is not necessary when using
Observable<Int>.interval
.