首页 > 解决方案 > 如何在kotlin中同步函数中的所有代码

问题描述

当我调用该函数时,我有一个具有一些“for 循环”的函数,然后第二个“for 循环”在第一个“for 循环”之前执行。在第一个“for 循环”中,我调用了一个方法并有一个调用方向 API 的代码。现在我想停止代码的执行,直到第一个 for 循环完成它的执行。我在谷歌上搜索但没有找到解决方案。请帮助某人,我该怎么做。下面我发布我的代码,请看一下。

private  fun setAllStopsInRange(stops: ArrayList<LatLng>) {
    arrayListOfRouteOriginMarker.forEach { it.remove() }
    stops.forEach { 
        arrayListOfRouteOriginMarker.add(map.addMarker(
            MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.blue_car))
                .position(
                    it
                )
        ))
    }
    RouteDestinationMarker?.remove()
    arrayListOfArea!!.forEach {
        if (it.areaName == binding.chooseAreaSpinner.selectedItem.toString()){
            destinationLatLong = it.areaLatLong
            RouteDestinationMarker = map.addMarker(MarkerOptions().position(destinationLatLong!!).title("Destination"))
        }
    }
    arrayListOfAllRoutePolylines.forEach { it.remove() }
    for (i in stops.indices){
        if ((clickedRouteOriginMarkerLatLong != null) && (clickedRouteOriginMarkerLatLong == stops[i]) && (i != stops.lastIndex)){
            Collections.swap(stops, stops.lastIndex,i)
        }
    }

    hashMapOfstopsLatLong = HashMap<LatLng, ArrayList<LocationInfo>>()


    
    stops.forEach {
        arraylistOfStopsLatLong = ArrayList<LocationInfo>()
        createRouteFromEachStop(it) // In this method I am calling api
    }

    for (latLong in arrayListOfRouteOriginInRangeLatLong.iterator()){
        Log.i(TAG, "setAllStopsInRange: sidf "+arrayListOfAllRouteOriginLatLong.size+", "+arrayListOfAllRouteOriginLatLong)
        var geocoder = Geocoder(this, Locale.getDefault())
        var addresses = geocoder.getFromLocation(
            latLong.latitude,
            latLong.longitude,
            1
        )

        val view = layoutInflater.inflate(R.layout.location_info_view, null)
        view.findViewById<TextView>(R.id.address_tv).text =  (addresses.get(0).subLocality+", "+addresses.get(0).locality)
        view.findViewById<TextView>(R.id.time_tv).text =  "7:00 AM"
        binding.locationInfoView.addView(view)

    }
    Log.i(TAG, "setAllStopsInRange: ddifesize "+hashMapOfstopsLatLong)
    hashMapOfstopsLatLong.forEach { t, u ->    // this for loop execute before above for loop
        Log.i(TAG, "setAllStopsInRange: tjjis "+t+" ,u is "+u) 
        u.forEach {
            val view = layoutInflater.inflate(R.layout.location_info_view, null)
            view.findViewById<TextView>(R.id.address_tv).text = it.addressInfo
            view.findViewById<TextView>(R.id.time_tv).text =  it.time
            binding.locationInfoView.addView(view)
        }
    }
}

标签: waitexecutionsynchronize

解决方案


推荐阅读