Android KTX + Kotlin coroutine combination

Request permission in the android, generally use requestPermissions and onRequestPermissionsResult combination to complete. However, this approach has a major drawback, as it can lead to code fragmentation and poor readability. Change the test way KTX call registerForActivityResult only in the activity or fragments, initialization time calls, cannot be used with triggered when clicking

Add the dependent

 implementation "Androidx. Activity: activity - KTX: 1.2.3"
 implementation "Androidx. Fragments: fragments - KTX: 1.3.3." "
Copy the code

Go straight to code


suspend fun ActivityResultCaller.permission(permission: String): Boolean {
    return callbackFlow {
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            this.offer(isGranted)
            close()
        }.launch(permission)
        awaitClose()
    }.first()
}

Copy the code

Train of thought

  1. Use the KTX library to use the split callcallbackPattern call
val caller = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
    // Returns the permission request result
}
caller.launch("Request specific permissions")

Copy the code
  1. Use kotlin’sCallbackFlowTo convert the callback mode to coroutineFlowcall
 callbackFlow<Boolean> {
     //callback register
 
    // It is indispensable to wait here for the call callback result
    awaitClose()
 }
Copy the code
  1. willflowConvert to a single return result
val result = callbackFlow<Boolean> {... }.first()Copy the code

use

In a scenario, after a button is clicked, scan code needs to be called and camera permission request needs to be made.

class MainActivity: AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?).{... lifecycleScope.launch {val result = permission(Manifest.permission.CAMERA)
            if(result){
                //todo
            }else{
                Toast.makeText(this@MainActivity."Please enable camera permissions.",Toast.LENGTH_SHORT).show()
            }
        }
       
    }

}

Copy the code

conclusion

Using kotlin coroutines not only improves execution efficiency, but also code readability. Much of the code that executes asynchronously can be written as if it executes synchronously (a drawback of this is that displaying the suspend call without the IDE’s logo can lead to misunderstandings).