Romman Sabbir
Romman Sabbir | Official

Romman Sabbir | Official

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

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

Romman Sabbir's photo
Romman Sabbir
·May 16, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • First,
  • Second,
  • Third (Final Step),

Yes, we can do that, EASILY!

By using: DI (Hilt) | FUN, right?

Let's check the snapshot::

(PNG Image, 4008 × 4772 pixels) — Scaled (20%).png

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

 
Share this