having a rough time with getting the user location...
# multiplatform
y
having a rough time with getting the user location applied 2 different approaches they both work but not in the way I want it. i get my current location but if I update it, it somehow gets the same old one until some time and about 6 to 7 emulator restars that It will get the location of the newly set location, code in thread.
First approach
Copy code
@SuppressLint("MissingPermission")
actual suspend fun getCoordinates(): Result<Flow<Coordinates?>> =
    runCatching {
        flow {
            val locationManager: LocationManager
            val context: Context = KoinPlatform.getKoin().get()
            locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager
            val listener = MutableStateFlow<Coordinates?>(null)
            locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                5,
                5f
            ) { location ->
                runBlocking {
                    listener.emit(Coordinates(location.latitude, location.longitude))
                }
                println("CORDS: ${location.latitude}, ${location.longitude}")
            }
          
        }
    }
second approach:
Copy code
@SuppressLint("MissingPermission")
actual suspend fun getCoordinates(): Result<Flow<Coordinates?>> =
    runCatching {
        flow {
            val context: Context = KoinPlatform.getKoin().get()
            val fusedLocationClient: FusedLocationProviderClient =
                LocationServices.getFusedLocationProviderClient(context)

            val currentLocationTask: Task<Location> =
                fusedLocationClient.getCurrentLocation(
                    PRIORITY_HIGH_ACCURACY,
                    null,
                )

            val listener = MutableStateFlow<Coordinates?>(null)

            currentLocationTask.addOnCompleteListener { task: Task<Location> ->

                if (task.isSuccessful) {
                    val result: Location? = task.result // Task result might be null
                    if (result != null) {
                        runBlocking {
                            println("CORDS: ${result.latitude}, ${result.longitude}")
                            listener.emit(Coordinates(result.latitude, result.longitude))
                        }
                    } else {
                        runBlocking {
                            listener.emit(null)
                        }
                    }
                } else {
                    runBlocking {
                        listener.emit(null)
                    }
                }
            }
            listener.collect {
                emit(it)
            }
        }
    }