Last active
October 25, 2023 18:14
-
-
Save DevSrSouza/ebe125a4b32617c7b86db7d0ccac4b8b to your computer and use it in GitHub Desktop.
Connecting to a service using Kotlin Coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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