How to check permission is granted in ViewModel?

前端 未结 3 1590
天涯浪人
天涯浪人 2021-02-08 19:53

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 gr

3条回答
  •  天涯浪人
    2021-02-08 20:17

    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()
    
        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")
            })
            ......
        }
    }
    

提交回复
热议问题