Reputation: 5002
Trying out RxSwift and trying to convert my network calls. I can't seem to display my data in the view because im not sure how I convert my observable to something my views can use. Here's an example of my request:
class SomeService {
let provider = Provider()
func getData() -> Observable<[Object]?> { // Returns json
return provider
.request(.getSomething())
.debug()
.mapArrayOptional(type: Object.self)
// Using Moya_Modelmapper map each item in the array
}
}
In my view controller I get the data:
let data = Service.getData()
print(data) ... <Swift.Optional<Swift.Array<MyApp.Item>>>
I have tried to subscribe to the response to the sequence but I don't know how I actually convert it to something like an array I can use in my view.
UPDATE: With answer implemented:
func itemsObserver() {
print("Time to print step 1") // This gets printed
data
.filter { $0 != nil }.map { $0! }
.subscribe(
onNext: { objects in
print(objects as Any)
print("Step 2") // This does not get executed at all
},
onCompleted:{ objects in
print(objects as Any) // This is ()
print("Complete") // This gets printed
}
).addDisposableTo(disposeBag)
}
itemsObserver()
Console output:
Time to print step 1
Service.swift:21 (getData()) -> subscribed
Service.swift:21 (getData()) -> Event next(Status Code: 200, Data Length: 141)
Service.swift:21 (getData()) -> Event completed
Service.swift:21 (getData()) -> isDisposed
()
Complete
Upvotes: 1
Views: 3533
Reputation: 33979
Update:
If your onNext
block isn't getting called at all, it's because data
never produced anything. Either your producer isn't producing any objects or mapArrayOptional
is not transforming them.
The onCompleted
block doesn't accept any arguments so the objects
var you have in it is meaningless/Void.
Try this:
let data = service.getData()
data
.filter { $0 != nil }.map { $0! } // this removes the optionality of the result.
.subscribe(onNext: { objects in
// in here `objects` will be an array of the objects that came through.
}).disposed(by: bag)
Upvotes: 1