Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call suspend function from Fragment or Activity?

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{...}
like image 978
Nurseyit Tursunkulov Avatar asked Nov 26 '19 04:11

Nurseyit Tursunkulov


People also ask

What is LifecycleScope launch?

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.

Can we call activity from fragment?

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.

What is ViewModelScope?

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.

Should be called only from a coroutine or another suspend function test?

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).


1 Answers

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)
    }
 }
}
like image 91
Nurseyit Tursunkulov Avatar answered Oct 06 '22 23:10

Nurseyit Tursunkulov