尽管为它分配了值,但我仍然收到空值

时间:2019-04-20 06:02:22

标签: android google-maps kotlin retrofit2 rx-java2

我想将API响应分配给Kotlin中的全局数组列表,但是在handleResponse函数之外,arraylist仍为null var一次性:一次性? =空     lateinit var mMap:GoogleMap     varsensorsData = ArrayList()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.

    showReading("Jxh7GGbk5S5KaBcnlQ4vUw")
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)

}
fun showReading(token: String) {

    disposable = client.sensorData(token)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(this::handleResponse)

}
fun handleResponse(sensorData: SensorNode) {

    this.sensorsData.add(sensorData)
    Log.d("SENSOR DATA", "" + sensorsData.get(0)) // Works
}
override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap
    Log.d("SENSOR DATA", "" + sensorsData.get(0)) // Return Null
    val sensor = LatLng(-6.8, 39.0)
    mMap.addMarker(MarkerOptions().position(sensor).title("Sensor Node 1"))
}
override fun onPause() {
    super.onPause()
    disposable?.dispose()
}

1 个答案:

答案 0 :(得分:1)

问题在于showReadingmapFragment.getMapAsync是两个异步调用,因此您无法保证哪个将首先完成。处理此问题的最快方法-同时启动它们,等待它们完成后再采取行动。

如果要使用反应流范例,可以执行以下操作:

  Single.create<GoogleMap> { emitter ->
            map.getMapAsync { emitter.onSuccess(it) }
        }.zipWith(sensorData(token), BiFunction<GoogleMap, SensorNode, Unit> { map, node -> 
            //do what you want with map and sensordata
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(this::handleResponse)