I am doing something that I thought should be straightforward: A WearOS tile shall display the data fetched via https request. I took the goals tile example from the documentation and added a callback for fetching the data in my Tile Service:
private val repoRetriever = EnergyRetriever()
private val callback = object : Callback<EnergyResult> {
override fun onFailure(call: Call<EnergyResult>?, t:Throwable?) {
Log.e("MainActivity", "Problem calling Energy API {${t?.message}}")
}
override fun onResponse(call: Call<EnergyResult>?, response: Response<EnergyResult>?) {
response?.isSuccessful.let {
val energyResult = response?.body()
Log.i("MainActivity", "SUCCESS! " + energyResult?.time + " - "+energyResult?.consumption + "kW")
EnergyRepository.setEnergy(energyResult);
getUpdater(getApplicationContext()).requestUpdate(GoalsTileService::class.java)
}
}
}
On the top of onTileRequest I initiate the request. I know that the tile will be rendered with the initial/old dataset, which is ok. I just want the tile to update once the data has been fetched:
override fun onTileRequest(requestParams: TileRequest) = serviceScope.future {
if (isNetworkConnected()) {
repoRetriever.getEnergyUpdate(callback)
}
// Retrieves data to populate the Tile.
val energyResult = EnergyRepository.getEnergy()
// Retrieves device parameters to later retrieve font styles for any text in the Tile.
val deviceParams = requestParams.deviceParameters!!
// Creates Tile.
Tile.builder()
// If there are any graphics/images defined in the Tile's layout, the system will
// retrieve them via onResourcesRequest() and match them with this version number.
.setResourcesVersion(RESOURCES_VERSION)
.setFreshnessIntervalMillis(5 * 60 * 1000)
// Creates a timeline to hold one or more tile entries for a specific time periods.
.setTimeline(
Timeline.builder().addTimelineEntry(
TimelineEntry.builder().setLayout(
Layout.builder().setRoot(
// Creates the root [Box] [LayoutElement]
layout(energyResult!!, deviceParams)
)
)
)
).build()
}
This is obviously not working right because the onTileRequest will finish before the HTTP request is done. I also understand that one shouldn't block this function to wait. RequestUpdate() causes problems because the tile won't update again within a 20 second period due to limitations imposed by Google. I've read that one can use Futures in onTileRequest to defer the actual update until the http request returns - however I haven't been able to figure out just how and for the life of me I can't find an understandable example that would apply to what I'm trying to do. I don't even know if using callbacks for the http request is advisable when using futures here.
Anyone got suggestions?