How to run CoroutineScope in RecyclerViewCursorAdapter on ViewHolder inside bindCursor{ }

1.1k views Asked by At

Note: I had implemented Coroutine Single Scope in RecyclerViewCursorAdapter but the app getting too slow when I change it to runBlocking it's working fine

Is there any way to execute CoroutineScope in ViewHolder inside bindCursor{ } on every scroll without impacting on performance ? I need to execute multiple queries from the database on every scroll and update the UI accordingly.

1

There are 1 answers

29
che10 On

I am pretty sure, there is a better way of doing what you are doing than to do it in adapter. I don't think that is correct, maybe you can use a callback via an interface or something.

But to return to your question, you should be easily be able to do this using lifeCycleScope

A LifecycleScope is defined for each Lifecycle object. Any coroutine launched in this scope is canceled when the Lifecycle is destroyed.

Since you have not mentioned whether it is an activity or an fragment that you are using, but the logic and functionality remains same for both. I am going to give you an example for Fragment

class MyFragment: Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            // Do stuff here
        }
    }
}

Just like that you can launch coroutines and it will be handled as per the lifecycle, you may need to pass the viewLifeCycleOwner to your Fragment, although as I said that is not recommended, you are better using an interface of sort and then computing in Fragment itself, but you can get the idea.