Kotlin / anko

Pleasant Android application development
Apache License 2.0
15.89k stars 1.29k forks source link

Support done() in async-uiThread #181

Closed netdur closed 8 years ago

netdur commented 8 years ago

Thanks for wonderful library

sometimes, for performance reasons, I would like to do some calculations off main thread then push results to ui, for example

async {
  val img = getImageFromCache().crop().filter(BLACKWHITE)
  uiThread {
    image.setImageBitmap(img)
  }
}

the problem, uiThread may not be called at all, I think extra done() function would solve this problem

Ribesg commented 8 years ago

As far as I know, uiThread will not be called if the context it was associated to is null (associated activity died for example), or something like that. Try using appCtx.uiThread.

But in the end I think that you're trying to reinvent the wheel. I highly suggest you use libraries like Picasso, Glide, Fresco or other similar libraries.

netdur commented 8 years ago

@Ribesg thanks, I indeed use Ion for network calls and image loading, I do not need async for this

what I need is to offload heavy calculations off main thread, in above example there no network calls, what I did is to load image off local cache, crop and apply a filter, those are heavy calculations, in this case even if activity is still on uiThread will not be called

another example using iconics https://github.com/mikepenz/Android-Iconics

async {
  // I need about 20 icons
  val android = new IconicsDrawable(this@MainActivity).icon(FontAwesome.Icon.faw_android).color(Color.RED).sizeDp(24)
  uiThread {
     image.setImageBitmap(android)
  }
}

uiThread in above example may not be called

mykhailo-gaidai commented 8 years ago

some wild guess here - if you're using Android Studio 2.x, make sure to disable Instant Run feature under the settings I've encountered issues with Kotlin code not being executed when it's on

netdur commented 8 years ago

@mykhailo-gaidai I do not have Instant Run feature on

carmas123 commented 8 years ago

There is a method to do a queued async tasks? So, to download an image l(like Picasso or Glide) into a listview we can use this async {} and then update the ui with uiThread...but if call for each Holder an async task is degree for the performance and I've more task.

yanex commented 8 years ago

As async() accepts everything as a receiver, you can pass something that will not be collected by GC for sure (System.out for example). In this case uiThread will be always executed. However, I admit there could be a reason for the done() function. It will be added in Anko 0.9.

yanex commented 8 years ago

onComplete() is added: https://github.com/Kotlin/anko/commit/f0b6ee5e81b4f54ab163ccb95c5ed30b6da3f012.

netdur commented 8 years ago

@yanex thank you