Android/Java: รอจนกว่าการปิดจะเสร็จสิ้น

ฉันมีปัญหากับการเขียนโปรแกรมอะซิงก์บางอย่างภายในแอปพลิเคชัน Android ฉันมีโค้ดบางส่วนในคลาส ClientLocation ที่รับค่า lat/lon ของผู้ใช้ แต่เมื่อได้โค้ดแล้ว จะต้องส่งโค้ดเหล่านั้นไปยังฟังก์ชัน เมื่อก้าวผ่านโค้ดฉันจะเห็นว่ามีการเรียกใช้การโทร repository.getDeals ก่อนที่จะป้อนการปิด gotLocation

นี่คือโค้ดที่สำคัญ:

...
this.repository = Repository.getInstance();
ClientLocation.LocationResult locationResult = new ClientLocation.LocationResult() {
    @Override
    public void gotLocation(Location location) {
        userLatitude = Double.toString(location.getLatitude());
        userLongitude = Double.toString(location.getLongitude());
    }
};
ClientLocation clientLocation = new ClientLocation();
clientLocation.getLocation(getApplication().getApplicationContext(), locationResult);
// I need the latitude and longitude values at this point in order to properly call getDeals
// currently when this is called the userLat/lon values are 0.0 because gotLocation didn't run yet
deals = repository.getDeals(searchQuery, maxDistInKm, userLatitude, userLongitude);

รูปแบบใดที่จะไม่เรียก getDeals ก่อนที่ gotLocation จะรันเสร็จ ใหม่สำหรับการเขียนโปรแกรมแบบอะซิงก์ ดังนั้นจึงยินดีต้อนรับเคล็ดลับอื่นๆ!


person ChristianF    schedule 14.12.2019    source แหล่งที่มา
comment
ดูสิ่งนี้ ขอฉันหน่อย รู้ที่นี่หากคุณต้องการความช่วยเหลือ :D   -  person a_local_nobody    schedule 14.12.2019
comment
นอกจากนั้น คุณยังสามารถพิจารณาย้ายโค้ดของคุณ (repository.getDeals) ไปที่ gotLocation เพื่อให้โค้ดดำเนินการทันทีที่ได้รับตำแหน่งจริงเท่านั้น   -  person a_local_nobody    schedule 14.12.2019


คำตอบ (1)


ที่นี่:

boolean isFinished  = false

 Thread {

     this.repository = Repository.getInstance();
     ClientLocation.LocationResult locationResult = new 
     ClientLocation.LocationResult() {
     @Override
     public void gotLocation(Location location) {
     userLatitude = Double.toString(location.getLatitude());
     userLongitude = Double.toString(location.getLongitude());
         isFinished = true
     }
   };



    while(true){

      if(isFinished ) break:
    }
   ClientLocation clientLocation = new ClientLocation()
   clientLocation.getLocation(getApplication().getApplicationContext(), locationResult);
    deals = repository.getDeals(searchQuery, maxDistInKm, 
    userLatitude, userLongitude);

    Thread.currentThread().interrupt()

}
person IceSoul    schedule 14.12.2019