How to check permission is granted in ViewModel?

I.S picture I.S · Jun 14, 2017 · Viewed 7.3k times · Source

I need to ask permission for contacts and when application starts I'm asking,in ViewModel part I need to call method which requires permission. I need to check permission is granted by user or not and then call, but for checking permission I need to have access Activity. while in my ViewModel I don't have a reference to Activity and don't want to have, How I can overcome, the problem?

Answer

Louis Tsai picture Louis Tsai · May 25, 2018

I just ran into this problem, and I decided to use make use of LiveData instead.

Core concept:

  • ViewModel has a LiveData on what permission request needs to be made

  • ViewModel has a method (essentially callback) that returns if permission is granted or not

SomeViewModel.kt:

class SomeViewModel : ViewModel() {
    val permissionRequest = MutableLiveData<String>()

    fun onPermissionResult(permission: String, granted: Boolean) {
        TODO("whatever you need to do")
    }
}

FragmentOrActivity.kt

class FragmentOrActivity : FragmentOrActivity() {
    private viewModel: SomeViewModel by lazy {
        ViewModelProviders.of(this).get(SomeViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ......
        viewModel.permissionRequest.observe(this, Observer { permission -> 
            TODO("ask for permission, and then call viewModel.onPermissionResult aftwewards")
        })
        ......
    }
}