Skip to content

Instantly share code, notes, and snippets.

@DevSrSouza
Last active October 25, 2023 18:14
Show Gist options
  • Save DevSrSouza/ebe125a4b32617c7b86db7d0ccac4b8b to your computer and use it in GitHub Desktop.
Save DevSrSouza/ebe125a4b32617c7b86db7d0ccac4b8b to your computer and use it in GitHub Desktop.
Connecting to a service using Kotlin Coroutines
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
suspend inline fun <reified S : Service, B : IBinder> Context.connectService(
crossinline onDisconnect: () -> Unit = {}
): Pair<B, ServiceConnection> = suspendCoroutine {
val connection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
onDisconnect()
}
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
it.resume(binder as B to this)
}
}
applicationContext.bindService(
Intent(this, S::class.java),
connection,
Context.BIND_AUTO_CREATE
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment