Last active
October 7, 2018 13:47
-
-
Save y2k/7e299f5bc63cf85c87f9dd03d5651f06 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// private suspend fun find(context: Context, destination: String): String? { | |
// val intent = Intent().setComponent(ComponentName(destination, IdentifierService::class.java.name)) | |
// return context.executeInService(intent) { ISharedIdentifier.Stub.asInterface(it).get() } | |
// } | |
suspend fun <T : Any> Context.executeInService(intent: Intent, extract: (IBinder) -> T): T? = | |
suspendCancellableCoroutine { continuation -> | |
val connection = createConnection(this, continuation, extract) | |
continuation.invokeOnCancellation { unbindService(connection) } | |
if (!bindService(intent, connection, Context.BIND_AUTO_CREATE)) | |
continuation.resume(null) | |
} | |
private fun <T : Any> createConnection( | |
context: Context, | |
continuation: Continuation<T?>, | |
extract: (IBinder) -> T | |
): ServiceConnection = | |
object : ServiceConnection { | |
private var result: T? = null | |
override fun onServiceConnected(name: ComponentName, service: IBinder) { | |
result = extract(service) | |
context.unbindService(this) | |
} | |
override fun onServiceDisconnected(name: ComponentName) { | |
continuation.resume(result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment