All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.github.hadilq.androidlifecyclehandler.SLife.kt Maven / Gradle / Ivy

Go to download

This library is a simplifier for unnecessary complex lifecycles of `androidx.lifecycle:lifecycle-extensions`.

The newest version!
package com.github.hadilq.androidlifecyclehandler

/**
 * Defines a [Life] object that can **sync** other lives with the same lifecycle.
 */
abstract class SLife : Life {

    private var isAlive = false

    private val lives = mutableSetOf()

    protected fun Life.sync(): Boolean = lives.add(this).also { if (isAlive) onBorn() }

    /**
     * It doesn't make sense to make [onBorn] and [onDie] methods thread-safe.
     */
    override fun onBorn() {
        if (!isAlive) {
            isAlive = true
            lives.forEach { it.onBorn() }
        }
    }

    /**
     * It doesn't make sense to make [onBorn] and [onDie] methods thread-safe.
     */
    override fun onDie() {
        if (isAlive) {
            isAlive = false
            lives.forEach { it.onDie() }
            lives.clear()
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy