简体   繁体   中英

RXSwift - How to recall an api

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)

   }

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)
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM