Reputation: 678
i created an observable for an api call and bind to a tableview. Now i am unclear how to call the same api once again? so as to do a refresh - say on an button click?. The following is my sample code.
Please let me know your thoughts it will be helpfull
var items : Observable<[String]>?
func viewDidLoad(){
items = fetchAllAnswers()
items.bindTo(....).addDisposableTo(bag)
}
func fetchAllAnswers() -> Observable<[String]>{
let api = Observable.create { (obsever: AnyObserver<[String]>) -> Disposable in
let answers = API.allAnswers()
obsever.onNext(answers)
obsever.onCompleted()
return AnonymousDisposable{
print("api dispose called")
}
}
return api
}
func onClickRefresh()
{
// how to call api here again?
// let items = fetchAllAnswers()
// items.bindTo(....).addDisposableTo(bag)
}
Upvotes: 1
Views: 1059
Reputation: 13651
func viewDidLoad() {
button.rx_tap.startWith().flatMap { _ in
fetchAllAnswers()
}.bindTo(...).addDisposableTo(bag)
}
flatMap
will transform taps to the result of the observable the closure returns, here a String
array.
startWith()
will force rx_tap
to emit a first value at subscription time, so that the first refresh behavior is kept.
Upvotes: 1
Reputation: 1360
it's simple. You may to use Variable for update your items:
let items = Variable([String]())
Next you must to bind items with your UITableView:
items.asObservable.bindTo(....).addDisposableTo(bag)
Next you may to update your items in subscriber:
fetchAllAnswers()
.subscribeNext { stringArray in
items.value = stringArray
}
.addDisposableTo(bag)
If you want to update your table by button click, you may to do next:
yourButton.rx_tap
.flatMap { void -> Observable<[String]> in
return fetchAllAnswers()
}
.subscribeNext { stringArray in
items.value = stringArray
}
.addDisposableTo(bag)
Upvotes: 2