RXSwift 平面地图
Posted
技术标签:
【中文标题】RXSwift 平面地图【英文标题】:RXSwift Flat Map 【发布时间】:2021-08-31 12:20:10 【问题描述】:我是 RXSwift 的新手,在我的应用程序中,我使用 Google Places Service 来获取 Place 坐标,然后我必须通过 get 请求访问我的 API,以检查获取的坐标是否在我们的操作区域内,我如何才能平面映射两者请求?
这是我的代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
progress.startAnimating()
GMSPlacesClient.shared().lookUpPlaceID(placesArray[indexPath.row].placeID) (place, error) in
//check if place is within the bounds array
if error == nil
if checkPlace(place: place!)
// valid location
else
// un valid location
self.progress.stopAnimating()
print(place?.coordinate.latitude)
func checkPlace(place : GMSPlace)->Bool
// Hit the api with get request
任何帮助将不胜感激
【问题讨论】:
【参考方案1】:我会用我的CLE library 做这样的事情:
import Cause_Logic_Effect
import RxSwift
import RxCocoa
import UIKit
extension ExampleViewController
func connect()
let api = API(session: URLSession.shared, activityIndicator: ActivityIndicator(), errorRouter: ErrorRouter())
let gmsPlace = tableView.rx.modelSelected(Place.self)
.map(\.placeID)
.flatMapLatest GMSPlacesClient.shared().rx.lookUpPlaceID($0)
.share()
let isValidPlace = gmsPlace
.flatMapLatest api.load(.checkPlace(place: $0))
.share()
Observable.zip(gmsPlace, isValidPlace)
.compactMap $0.1 ? $0.0 : nil
.bind(onNext: place in
// the place is valid, do something with it.
)
.disposed(by: disposeBag)
// let the user know that the place is not valid.
Observable.zip(gmsPlace, isValidPlace)
.compactMap $0.1 ? nil : "\($0.0.name) is not a valid place."
.bind(onNext: presentScene(animated: true) message in
UIAlertController(title: "Sorry", message: message, preferredStyle: .alert)
.scene $0.connectOK()
)
.disposed(by: disposeBag)
api.isActive
.bind(to: activityIndicatorView.rx.isAnimating)
.disposed(by: disposeBag)
api.error.map(\.localizedDescription)
.bind(onNext: presentScene(animated: true) message in
UIAlertController(title: "Error", message: message, preferredStyle: .alert)
.scene $0.connectOK()
)
.disposed(by: disposeBag)
extension Endpoint where T == Bool
static func checkPlace(place: GMSPlace) -> Endpoint
fatalError() // Create the URLRequest and function for processing the response here
extension Reactive where Base: GMSPlacesClient
func lookUpPlaceID(_ id: String) -> Observable<GMSPlace>
Observable.create [base] observer in
base.lookUpPlaceID(id) place, error in
if let place = place
observer.onSuccess(place)
else
observer.onError(error ?? RxError.unknown)
return Disposables.create()
【讨论】:
以上是关于RXSwift 平面地图的主要内容,如果未能解决你的问题,请参考以下文章
我可以从 rxSwift map-Function 引发错误吗