How to execute any operations in an *Adapter or a *ViewHolder under the foreground activity's lifecyclescope?

Senior Android Engineer from Bangladesh. Love to contribute in Open-Source. Indie Music Producer.
If get to know something new by reading my articles, don't forget to endorse me on LinkedIn
Yes, we can do that, EASILY!
By using: DI (Hilt) | FUN, right?
Let's check the snapshot::

First,
We have an abstract class "ActivityAdapter" that takes "Context" as a parameter and contain an Single API "getCoroutineScope()" to get the Activity's LifecycleScope (Force Casting) as a callback.
Second,
We are receiving the "Context" in the "TestAdapter" with the help of "DI, THE SAVIOUR" :D and adapter is extended from "ActivityAdapter". Now we can access the LifecycleScope of foreground activity's in the *Adapter or *ViewHolder in runtime.
Third (Final Step),
Register the "TestAdapter" in the any module which is bound to Activity lifecyle or annotated with "@InstallIn(ActivityComponent::class)". This module make sure that "TestAdapter" receive the foreground activity context as a parameter when client "@Inject" "TestAdapter" in an Activity or a Fragment.
Happy Coding...




