androidandroid-fusedlocationandroid-task

Get the result of a Task without a callback


I am currently trying to migrate all my location calls to use the new Task model flow but one question I have is that is there a way to get the result of a task without having to wait for a callback?

The reason I ask is because I need to get the last location inside an async task before I save something to my database but since I am already in another thread I shouldn't have to worry about something taking time plus isnt having a callback inside an async task bad?

The documentation says task.getResult() only gives you a result once it has completed

So my question is, is there anyway to execute this synchronously?

using this as reference

https://developer.android.com/training/location/retrieve-current.html


Solution

  • If you are already in a background thread, you can indeed execute the task synchronously. For this, the new API is now:

    Result result = Tasks.await(task);