2017-03-10 84 views
0

我想創建一個搜索欄是通過MKLocalSearch與請求搜索地址,並使用RXSwift並結合RXCocoaRXSwift flatmap從異步完成處理程序返回

到目前爲止,我已經做了以下 1.過濾器和反跳,以避免過多的請求:

let searchRes = searchBar.rx.text 
    .orEmpty 
    .filter { query in 
     return query.characters.count > 4 
    } 
    .debounce(1, scheduler: MainScheduler.instance) 
  • 所得串查詢是圖:ED創建MKLocationSearch然後flatMapp:ED返回MKMapItems的陣列是能夠將數組綁定到tableView的項目:

    searchRes.map{query -> MKLocalSearch in 
        let request = MKLocalSearchRequest() 
        request.naturalLanguageQuery = query 
        request.region = self.mapView.region 
        return MKLocalSearch(request: request) 
    }.flatMapLatest{search -> Observable<[MKMapItem]> in 
        search.start(completionHandler:{(response, error) in 
         let items: Variable<[MKMapItem]> = Variable([]) 
         if let resp = response { 
          //need to return the result form this 
          // i.e. items.value = response.mapItems 
         } 
         //can not return from here since the request is async 
        } 
    }.bindTo //continue to bind to tableview 
    
  • 怎麼可以這樣使用RXSwift做的,我找不到任何相關的例子

    回答

    3

    你必須創建一個可觀察與ansync請求。你可以定義下面的方法來做到這一點:

    func mapItems(for searchRequest: MKLocalSearch) -> Observable<[MKMapItem]> { 
        return Observable.create { observer in 
         searchRequest.start(completionHandler: { (response, error) in 
          if let error = error { 
           observer.onError(error) 
          } else { 
           let items = response?.mapItems ?? [] 
           observer.onNext(items) 
           observer.onCompleted() 
          } 
         }) 
    
         return Disposables.create { 
          searchRequest.cancel() 
         } 
        } 
    } 
    

    然後,你可以使用flatMapLatest與方法:

    searchRes 
        .map { query -> MKLocalSearch in 
         let request = MKLocalSearchRequest() 
         request.naturalLanguageQuery = query 
         request.region = self.mapView.region 
         return MKLocalSearch(request: request) 
        } 
        .flatMapLatest{ [unowned self] search -> Observable<[MKMapItem]> in 
         self.mapItems(for: search) 
        } 
        .bindTo(.... 
    
    +0

    謝謝你,還在探索RX深處,這部分一直沒有得到很好的documentend – EmilDo

    相關問題