Skip to content

Delegation Example: Log events onStart() and onResume()

Devrath edited this page Feb 28, 2024 · 2 revisions

Code for using the Analytics and Clearing resources

class MainActivity : ComponentActivity(),
    IAnalyticsLogger by IAnalyticsLoggerImpl(),
    IClearResources by IClearResourcesImpl()
{

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // ---> We call the method of our AnalyticsLoggerImpl here to register the activity
        registerLifeCycleOwner(this)

        setContent {
            DelegationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) { Text(text = "Hello") }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        // ---> We Call our implementation here
        clearResources()
    }

}

Code for Analytics

interface IAnalyticsLogger {
    fun registerLifeCycleOwner(lifecycleOwner: LifecycleOwner)
}

class IAnalyticsLoggerImpl : IAnalyticsLogger, LifecycleEventObserver {

    // We call this in our activity and register our activity here
    override fun registerLifeCycleOwner(lifecycleOwner: LifecycleOwner) {
        lifecycleOwner.lifecycle.addObserver(this)
    }

    // This is called on event of each of our activity
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when(event) {
            Lifecycle.Event.ON_RESUME -> println("Screen is in foreground")
            Lifecycle.Event.ON_PAUSE -> println("Screen is not in foreground anymore")
            else -> Unit
        }
    }

}

Code for Clearing resource

interface IClearResources {
    fun clearResources()
}

class IClearResourcesImpl : IClearResources {

    override fun clearResources() {
        println("Resources are cleared!")
    }

}
Clone this wiki locally