I want to request permission and do it by nonblocking function. Since I need Context I can not call it from ViewModel. How to give a default UI scope for fragment and call suspend function like this:
class MapsFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
launch {
withContext(Dispatcher.Main){
checkLocationPermission().await()
}
}
}
}
suspend fun checkLocationPermission():Boolean{...}
LifecycleScope. A LifecycleScope is defined for each Lifecycle object. Any coroutine launched in this scope is canceled when the Lifecycle is destroyed. You can access the CoroutineScope of the Lifecycle either via lifecycle.
Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.
ViewModelScope: A viewModelScope is defined for each viewModel in our app. It is bound to ViewModel's lifecycle and will handle cancellation of all coroutines, when the ViewModel onClear() is called.
Suspend function should be called only from a coroutine. That means to call a suspend function you need to use a coroutine builder, e.g. launch , async or runBlocking (recommended to use only in unit tests).
In documentation https://developer.android.com/topic/libraries/architecture/coroutines said that I can use androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01
ktx.
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
val params = TextViewCompat.getTextMetricsParams(textView)
val precomputedText = withContext(Dispatchers.Default) {
PrecomputedTextCompat.create(longTextContent, params)
}
TextViewCompat.setPrecomputedText(textView, precomputedText)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With