Skip to content

Instantly share code, notes, and snippets.

@tizisdeepan
Last active April 22, 2019 06:41
Show Gist options
  • Save tizisdeepan/f876fd76e0d42c15a28a01a6dc1966ce to your computer and use it in GitHub Desktop.
Save tizisdeepan/f876fd76e0d42c15a28a01a6dc1966ce to your computer and use it in GitHub Desktop.
A simple Kotlin class to run a function safely on a UiThread anywhere anytime without crashing the application. Avoids crashes, ANRs and logs the problem efficiently.
import android.content.Context
import org.jetbrains.anko.runOnUiThread
class RunOnUiThread(var context: Context?) {
fun safely(dothis: () -> Unit) {
if (context != null) {
context?.runOnUiThread {
try {
dothis.invoke()
} catch (e: Exception) {
//Replace with your logger
MLog.e("runonui - ${context!!::class.java.canonicalName}", e.toString())
e.printStackTrace()
}
}
}
}
}
@tizisdeepan
Copy link
Author

USAGE

RunOnUiThread(Context Reference).safely {
      //doSomething
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment