Lifecycle

Lifecycle has 2 interfaces:

  • LifecycleOwner – Objects with a lifecycle e.g. Activities and Fragments
  • LifecycleObserver – Observe LifecycleOwners and get notified on lifecycle changes

LiveData is lifecycle aware because it is a Lifecycle Observer. This is why we feed in the LifecycleOwner (in this case the Activity) argument when we call the LiveData’s observer() method. LiveData will also know when the Activity is destroyed and automatically unsubscribe the Observers to prevent memory leaks.

To implement this without LiveData:

import ...

class MainActivity : AppCompatActivity() {

    private lateinit var myClass: MyClass

    // Contains all the views
    private lateinit var binding: ActivityMainBinding

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

        // Use Data Binding to get reference to the views
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        myClass = MyClass(this.lifecycle) // Instantiate your observer class and pass in the Activity lifecycle (this.lifecycle) as the observed object
    }
}
import ...
class MyClass(lifecycle: Lifecycle) : LifecycleObserver { // Set this class up as an observer

    init {
        lifecycle.addObserver(this) // Initialise the observer to the object passed in to the constructor
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START) // Choose a lifecycle event
    fun startFunction() { // This function will be called on the lifecycle event specified
        // Start something
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stopFunction() {
        // Stop something
    }
}