Permission Request inside ViewModel or Presenter
TurKurT656 opened this issue ยท 4 comments
I this section: Injection you mentioned that we can use the permission request inside our presenter. I've looked into the library and I saw that permissionBuilder
function is a ktx function on Fragment
and Activity
.
I there a sample code for this? I wanna know how can I use this lib inside my ViewModel
s.
It depends on which DI container you are using.
Generally, you can create the PermissionRequest
from outside and pass it to the view-model.
E.g. using Dagger:
class MyViewModel @Inject constructor(val request: Lazy<PermissionRequest>): ViewModel()
@Module
object MyModule {
@Provides
fun viewModelFactory(request: Lazy<PermissionRequest>): ViewModelProvider.Factory = TODO()
@Provides
fun permissionRequest(activity: MyActivity): PermissionRequest =
activity.permissionsBuilder(Manifest.permission.ACCESS_FINE_LOCATION).build()
}
Just an important tip: the WIKI mentions the presenter instead of the view-model since the Android's view-model has a longer lifecycle than the activity after an orientation change occurs. This means that if you are using an activity without a fixed orientation and a view model, the permission request injected with the code above can leak. You can change that implementation providing the current activity to create a fresh PermissionRequest
everytime if you have not a fixed orientation and you are using the Android's view-model.
I'm using koin for DI. In this way aren't we creating a loop?
Activity <- PermissionRequest <- ViewModel <- Activity
It would be great if the PermissionRequest builder doesn't need fragment or activity. (for example creating it without activity or fragment and passing activity or fragment in addListener function or creating it with only applicationContext. I don't know if it's possible or not. I'm just thinking loudly :D )
We aren't creating a loop since the Activity is used to create both the ViewModel
and its dependencies only once.
Unfortunately, we can't create a PermissionRequest
without an application context for the Android's permissions limitations.
To display the dialog which allows the user to accept the permissions, an Activity
is required. This library could workaround it with a Application.ActivityLifecycleCallbacks
but it would be an horrible workaround since this library should make some assumptions on how the permissions are requested by the users of this library.
Anyway, if you would not like to implement the solution I posted above, you can still inject it in the Activity and communicate the request and the response of the PermissionRequest
back and forth with the ViewModel
.
I'm closing this, feel free to re-open it if you have other doubts.