How to implement timer with Kotlin coroutines

Edit: note that the API suggested in the original answer is now marked @ObsoleteCoroutineApi: Ticker channels are not currently integrated with structured concurrency and their api will change in the future. You can now use the Flow API to create your own ticker flow: import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun tickerFlow(period: Duration, … Read more

Existing 3-function callback to Kotlin Coroutines

In this particular case you can use a general approach to convert a callback-based API to a suspending function via suspendCoroutine function: suspend fun CameraManager.openCamera(cameraId: String): CameraDevice? = suspendCoroutine { cont -> val callback = object : CameraDevice.StateCallback() { override fun onOpened(camera: CameraDevice) { cont.resume(camera) } override fun onDisconnected(camera: CameraDevice) { cont.resume(null) } override fun … Read more

What is the difference between launch/join and async/await in Kotlin coroutines

launch is used to fire and forget coroutine. It is like starting a new thread. If the code inside the launch terminates with exception, then it is treated like uncaught exception in a thread — usually printed to stderr in backend JVM applications and crashes Android applications. join is used to wait for completion of … Read more

Call Kotlin suspend function in Java class

First, add org.jetbrains.kotlinx:kotlinx-coroutines-jdk8 module to your dependencies. In your Kotlin file define the following async function that corresponds to Java style of writing async APIs: fun doSomethingAsync(): CompletableFuture<List<MyClass>> = GlobalScope.future { doSomething() } Now use doSomethingAsync from Java in the same way as you are using other asynchronous APIs in the Java world.

The AsyncTask API is deprecated in Android 11. What are the alternatives?

private WeakReference<MyActivity> activityReference; Good riddance that it’s deprecated, because the WeakReference<Context> was always a hack, and not a proper solution. Now people will have the opportunity to sanitize their code. AsyncTask<String, Void, MyPojo> Based on this code, Progress is actually not needed, and there is a String input + MyPojo output. This is actually quite … Read more