AndroidPub
Published in

AndroidPub

Kotlin DSL for runtime permissions

Shot on my Pixel 3a XL

A while back I open-sourced an Android library eazypermissions for runtime permissions which allows you to request permission within coroutines (no callback yay 🎉) and has support for LiveData as well. If you are interested you can read more about it 👇

The library now offers a Kotlin DSL to request permissions. In this post, we will discuss the DSL API and how to request permissions using the DSL. Let’s get started.

Kotlin DSL for requesting permissions

While requesting permissions three things that matter are permissions, the request code, and the result. The DSL API focuses on these three things and allows you to request permissions cleanly and concisely. Let’s see how.

If you are requesting permission in Activity/Fragment you can request permissions as shown below.

Now let’s understand the above DSL.

The requestPermissions function is an extension function on Activity and Fragment so you can call it directly from activity and fragment. It takes vararg of permissions that you want to request and lambda with a receiver on PermissionRequest. Since it is a lambda with a receiver on PermissionRequest you have direct access to members of PermissionRequest. Within lambda, you initialize two members of PermissionRequest, requestCode and resultCallback.

Here is the definition of PermissionRequest class.

resultCallback is again a lambda with a receiver on PermissionResult and the library will invoke this callback for a result. Inside the lambda, you can directly refer permission result as this. PermissionResult is nothing but the simple sealed class which wraps all possible outcomes i.e Permission granted, denied, denied permanently and show rational.

Here are the signatures of requestPermissions extension functions on Activity and Fragment.

If you are requesting permission outside your Fragment/Activity you can request permissions as shown below.

The only difference here is you need to call PermissionManager.requestPermissions which takes an instance of Fragment/Activity as an additional parameter. The extension function we saw previously internally delegates call to this function.

Here are the signatures of PermissionManager.requestPermissions functions.

How you include the library in your project.

implementation 'com.sagar:dslpermission:2.0.0'

That’s all I have for this new Kotlin DSL feature. Head over to the GitHub repo below for more details about the library.

If you have any suggestions please feel free to comment below or you can reach out to me on Twitter.

That’s it, for now, folks 🙂 Until next time 👋

Happy coding 😃

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store