假如要实现这样的一个功能,基于高德地图API搜索用户指定的地点,然后获取周边1公里的所有酒店。我们都知道,高德地图的地理解析和Poi搜索都是异步接口。如果不使用RxJava的话,只能是按顺序在地理解析的GeocodeListener回调接口中再次发起Poi搜索。如下:
package com.centros.rxjava2amap
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
import com.amap.api.maps.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.GeocodeQuery
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.services.routepoisearch.RoutePOISearchQuery
const val city = "广州"
const val keyword = "饭店|酒店"
const val radius = 1000
class MainActivity : AppCompatActivity(), GeocodeSearch.OnGeocodeSearchListener, PoiSearch.OnPoiSearchListener {
private lateinit var edittext:EditText
private lateinit var button:Button
private lateinit var listView:ListView
private var hotels:List<String> ?= null
private lateinit var adapter:ArrayAdapter<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
edittext = findViewById(R.id.edittext) as EditText
button = findViewById(R.id.button) as Button
listView = findViewById(R.id.listview) as ListView
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, hotels)
listView.adapter = adapter
button.setOnClickListener {
view -> //发起地理解析,获取经纬度坐标
val geocodeSearch = GeocodeSearch(this@MainActivity)
geocodeSearch.setOnGeocodeSearchListener(this@MainActivity)
geocodeSearch.getFromLocationNameAsyn(GeocodeQuery(edittext.text?.toString(), city))
}
}
override fun onRegeocodeSearched(p0: RegeocodeResult?, p1: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onGeocodeSearched(geocodeResult: GeocodeResult?, errCode: Int) {
if(errCode==1000){ //1000为搜素成功
//发起Poi搜索
val latLonPoint = geocodeResult!!.geocodeAddressList[0].latLonPoint
val poiSearch = PoiSearch(this@MainActivity,PoiSearch.Query(keyword, city))
poiSearch.bound = PoiSearch.SearchBound(latLonPoint, radius)
poiSearch.setOnPoiSearchListener(this@MainActivity)
poiSearch.searchPOIAsyn()
}
else
throw AMapException("地址解析失败")
}
override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onPoiSearched(poiResult: PoiResult?, errCode: Int) {
if(errCode==1000){
hotels = poiResult!!.pois?.map { it.title }
if(hotels!!.isNotEmpty())
adapter.notifyDataSetChanged()
else
Toast.makeText(this@MainActivity,"没有在${keyword}附近找到饭店",Toast.LENGTH_LONG)
.show()
}else{
throw AMapException("周边搜索失败")
}
}
}
以上的代码看上去很简短,逻辑也很清晰,就是先解析地址的经纬度坐标,然后在地理解析的回调接口中发起周边搜索。这是因为目前业务太简单了,只解析饭店名称有个屁用啊,接下来还要从数据库中读取饭店的房间、价格啊,那时候逻辑就很复杂了,代码也显得非常零散。RxJava 的优点就是链式调用,逻辑清晰明了,线程切换跟吃饭一样简单。接下来我们就来看看怎么用RxJava实现以上的功能。
首先我们要做的分别用Observable封装地理位置搜索和周边搜索:
package com.centros.rxjava2amap
import android.content.Context
import com.amap.api.services.core.LatLonPoint
object RxAMap {
//地理位置解析,根据名称解析经纬度坐标
fun geoSearch(context: Context, location: String, city: String) =
GeocodeSearchObservable(context, location, city)
//周边搜索
fun poiSearch(context: Context, latLonPoint: LatLonPoint, radius:Int, keywords:String, city:String) =
PoiSearchObservable(context,latLonPoint, radius,keywords,city)
}
package com.centros.rxjava2amap
import android.content.Context
import com.amap.api.services.geocoder.GeocodeQuery
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.MainThreadDisposable
/**
* Created by Centros on 2018/4/17.
*/
class GeocodeSearchObservable(private val context: Context, private val location: String, private val city: String) : Observable<GeocodeResult>() {
override fun subscribeActual(observer: Observer<in GeocodeResult>) {
val geocodeSearch = GeocodeSearch(context)
val query = GeocodeQuery(location, city)
val listener = Listener(geocodeSearch, observer)
observer.onSubscribe(listener)
geocodeSearch.setOnGeocodeSearchListener(listner)
geocodeSearch.getFromLocationNameAsyn(query)
}
internal class Listener(private val geocodeSearch: GeocodeSearch, private val observer: Observer<in GeocodeResult>) : MainThreadDisposable(), GeocodeSearch.OnGeocodeSearchListener {
override fun onGeocodeSearched(geocodeResult: GeocodeResult, i: Int) {
if (!isDisposed) { //如果主线程没有被关闭
if (i == 1000)
observer.onNext(geocodeResult)
else
observer.onError(Throwable("定位失败"))
}
}
override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult, i: Int) {
}
override fun onDispose() {
}
}
}
看到没,我们用Observable封装了地理解析,发射的就是地理解析回调结果GeocoedeResult.实际上最主要的是用 MainThreadDisposable封装了OnGeocodeSearchListener, 为什么用MainThreadDisposable?自己去看Rxjava的文档,我不啰嗦。接下来我们继续封装周边搜索结果。
package com.centros.rxjava2amap
import android.content.Context
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.MainThreadDisposable
/**
* Created by Centros on 2018/4/17.
*/
class PoiSearchObservable(private val context: Context, private var latLonPoint: LatLonPoint,private var radius:Int, private val keyword: String, private val city: String) : Observable<PoiResult>() {
override fun subscribeActual(observer: Observer<in PoiResult>) {
val query = PoiSearch.Query(keyword,"",city)
val poiSearch = PoiSearch(context, query)
poiSearch.bound = PoiSearch.SearchBound(latLonPoint,radius)
val listener = Listener(observer)
observer.onSubscribe(listener)
poiSearch.searchPOIAsyn()
}
class Listener(var observer: Observer<in PoiResult>):MainThreadDisposable(),PoiSearch.OnPoiSearchListener{
override fun onDispose() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onPoiSearched(p0: PoiResult?, p1: Int) {
if(p1==1000)
p0?.let { observer.onNext(it) }
else
observer.onError(Throwable("Poi搜索失败"))
}
}
}
现在我们看一下怎么链式调用这两个搜索。
package com.centros.rxjava2amap
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
const val city = "广州"
const val keyword = "饭店|酒店"
const val radius = 1000
class MainActivity : AppCompatActivity() {
private lateinit var edittext: EditText
private lateinit var button: Button
private lateinit var listView: ListView
private var hotels: List<String>? = null
private lateinit var adapter: ArrayAdapter<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
edittext = findViewById(R.id.edittext) as EditText
button = findViewById(R.id.button) as Button
listView = findViewById(R.id.listview) as ListView
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, hotels)
listView.adapter = adapter
button.setOnClickListener { view ->
linkStyleSearch()
}
}
//链式搜索
fun linkStyleSearch() {
//发起地理解析,获取经纬度坐标,然后发起周边搜索,获取周边的酒店名称列表
RxAMap.geoSearch(this@MainActivity, edittext.text.toString(), city)
.subscribeOn(Schedulers.io())
.flatMap {
log("经纬度坐标为:${it.geocodeAddressList[0].latLonPoint.toString()}")
RxAMap.poiSearch(this@MainActivity, it.geocodeAddressList[0].latLonPoint,
radius, keyword, city)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
hotels = it.pois.map { it.title }
if (hotels!!.isNotEmpty())
adapter.notifyDataSetChanged()
}
}
}
fun Context.log(msg: String) {
val tag = this::class.java.simpleName
Log.i(tag, msg)
}
大功告成!以上就是怎么用RxJava封装回调接口的示例,以上示例可能会有异常,自己处理一下吧。