1

I am sending location data using co routines in workmanager. I tried just using the workmanager but it does not do async work I tried ListenableWorkmanager but that was too complicated for me so I am trying to use coroutines.

override fun doWork(): Result {

     CoroutineScope(IO).launch  {
        val location = work()
         fusedLocationClient!!.removeLocationUpdates(locationCallback)
          string = logData(location)
     }
        return if(JSONObject(string).get("status") == "1"){
            Result.success()
        }else{
            Result.retry()
        }

    }

I am having trouble on how to return the location from the work function

 private suspend fun work():Location{
...............

 fusedLocationClient!!.lastLocation.addOnSuccessListener { location ->
            if (location != null) {
                mCurrentLocation = location
          // how do I send this location back to the fuction??
            }
        }.addOnFailureListener {
            mLog.i(TAG, it.message)
        }
return mCurrentLocation // if I do this could be a null right?
}
Pemba Tamang
  • 458
  • 3
  • 16

1 Answers1

0

The Worker class only supports synchronous work. This means that when you return the result, the code in your worker needs to have completed its execution.

In your case you should use a ListenerWorker (or a CoroutineWorker if you prefer to use Kotlin).

Take a look at last year ADS talk on WorkManager, it covers this a bit. You can also view my talk Embracing WorkManager that covers the difference between the different Worker classes.

pfmaggi
  • 6,116
  • 22
  • 43
  • hey I went through your slides and a lot of posts your presentation is good but I am not good with kotlin and among the posts I found one that is doing what I want.. is this the proper way to do it?? https://stackoverflow.com/questions/54083654/how-do-i-run-a-listenableworker-work-on-a-background-thread – Pemba Tamang Sep 03 '19 at 17:07
  • yeah, you can follow that answer. – pfmaggi Sep 03 '19 at 17:59
  • Please, don't use coroutines inside a Worker class, use a CoroutineWorker or use a ListenableWorker. – pfmaggi Sep 04 '19 at 11:16
  • there are not much examples to go on, I am new and I could not understand much of the code still I will give it a try. Thank u very much for your help. – Pemba Tamang Sep 04 '19 at 15:26
  • I am trying to work with ListenerWorker but the SettableFuture.create is private according to the lint warning and cannot be used. Is that correct or is it a bug as discussed here https://stackoverflow.com/a/52825547/8528047 because I am still getting it on `androidx.work:work-runtime:2.2.0` – Pemba Tamang Sep 04 '19 at 15:39
  • or will this code with a countdown latch will work https://stackoverflow.com/a/50425201/10800406 – Pemba Tamang Sep 04 '19 at 15:45