Today I noticed a wrong usage in code which looks like this:
runInBackground(
{
if (null == activity) {
return@runInBackground
}
…
hud.dismiss()
}
)
The problem is that hud.dismiss()
should run on the UI thread, and that method is annotated with @UiThread
. However the IDE is unable to flag that, because there is no information for it to figure out that the runnable block has to run in a background thread:
public static void runInBackground(@NonNull Runnable r)
{
assertNotNull(r);
if (Looper.myLooper() != Looper.getMainLooper()) {
r.run();
} else {
AsyncTask.THREAD_POOL_EXECUTOR.execute(r);
}
}
Two things I imagine could be done are flagging the SAM/lambda with annotations, adding manually the @WorkerThread
annotation which would tell the IDE this information. More convenient of course would be to somehow be able to flag the @NonNull Runnable r
as a @WorkerThread
, which would make whatever is passed as parameter inherit this annotation.
Is this the correct place to request a feature request which would aid with these situations? I’m not sure if this is something that Kotlin has to implement or is a limitation of annotations which can’t be worked around.
As a workaround I write the SAM block as a separate private function which can be annotated, but this can lead to many parameters being passed over and over across thread boundaries and manual bookkeeping.