Android View Lifecycle Extensions

Overview

Android View Lifecycle Extensions

Extensions for Android View class that let you access a view lifecycle without having to create a custom view (extend a View)

Maven Central

Dependency

app/build.gradle

dependencies {
    implementation "com.gorisse.thomas:android-view-lifecycle:1.0.1"
}

Usage

View Class Kotlin Extensions

No need for custom view since all properties and functions are defined as View extensions.

val lifecycle = findViewById(R.id.frameLayout).lifecycle
val imageView = ImageView(context)
imageView.lifecycleScope.launchWhenCreated {
    (imageView.parent as View).isVisible = true
     loadSlideShow(imageView.width, imageView.height)
}

View Lifecycle

Listen or execute when a View lifecycle state occurred

  • Invoke an action every time the view becomes resumed
view.lifecycle.addObserver(onResume = {
    refreshData()
})
  • Invoke actions once, when the view is at least at a state
view.doOnResume {
    startWelcomeAnimation(view)
}
view.doOnPause {
    stopWelcomeAnimation(view)
}

= If the view is already resumed the action will be performed immediately, otherwise the action will be performed after the view is next resumed In all the cases, your action will be invoked only one time.

  • Perform an action when the view is destroyed:
view.doOnDestroy {
    removeListener(view)
}

View LifecycleScope

Launch a coroutine and auto cancel it when the view sate is destroyed

  • Launches and runs the given block when the view Lifecycle state is at least resumed. The returned Job will be cancelled when the view is destroyed.
texView.lifecycleScope.launchWhenCreated { // Launch on Dispatchers.Main
    val data = withContext(Dispatchers.IO) { // Dispatchers.IO for background task
        loadNetworkData() // Suspend function making http calls
    }
    texView.text = data // Dispatchers.Main for UI change
}

= When the view is detached or the Fragment or FragmentActivity container is destroyed, if loadNetworkData() is not finished, the network call is cancelled.

  • Launch a repeating call and auto cancel it when the view is destroyed (TimerTask Coroutine equivalent). The returned Job will be cancelled when the view is destroyed.
textView.lifecycleScope.launchWhenCreated {
    while (isActive) {
        view.text = "${System.currentTimeMillis()}" // Dispatchers.Main
        withContext(Dispatchers.IO) { // Dispatchers.IO for waiting in background
            delay(1000) // Wait 1 second
        }
    }
}

= When the view is detached or the Fragment or FragmentActivity container is destroyed, the while loop stops.

You might also like...
View
View "injection" library for Android.

Kotter Knife Deprecated: This was a terrible idea because it allocates an object for every view reference. Do not use, and do not use anything like it

Android sliding panel that is part of the view hierarchy, not above it.
Android sliding panel that is part of the view hierarchy, not above it.

sliding-panel A ViewGroup that implements a sliding panel that is part of the view hierarchy, not above it. Difference from other libraries All other

🍞 The ultimate breadcrumbs view for Android!
🍞 The ultimate breadcrumbs view for Android!

KrumbsView The ultimate breadcrumbs view for Android! Inspired by JotterPad's breadcrumbs. Features: Custom typeface (from /assets and /res/font folde

:speedboat: Floating navigation view for displaying a list of items dynamically on Android.
:speedboat: Floating navigation view for displaying a list of items dynamically on Android.

Submarine Fully customizable floating navigation view for listing items dynamically on Android. Including in your project Gradle Add below codes to yo

A simple project that describes the relationship between the view and it's viewmodel in android development
A simple project that describes the relationship between the view and it's viewmodel in android development

View-ViewModel-Communication A simple project that describes the relationship between the view and it's viewmodel in android development In MVVM archi

Custom Sneaker view for Android.
Custom Sneaker view for Android.

SneakerView How to install ? You can add the library to your project using jitpack.io. Add the code below to your project's settings.gradle file. all

ZoomHelper will make any view to be zoomable just like Instagram pinch-to-zoom
ZoomHelper will make any view to be zoomable just like Instagram pinch-to-zoom

ZoomHelper ZoomHelper will make any view to be zoomable just like the Instagram pinch-to-zoom. 😉 Installation ZoomHelper is available in the JCenter,

Arc Layout is a view group with which you can add a arc-shaped container in your layout.
Arc Layout is a view group with which you can add a arc-shaped container in your layout.

ArcLayout Arc Layout is a view group with which you can add a arc-shaped container in your layout. Two main variables are the direction and the curvat

A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.
A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.

한국어 No more boilerplate adapters and view holders. Slush will make using RecyclerView easy and fast. The goal of this project is to make RecyclerView,

Comments
  • Access lifecycleOwner before view attached would be wrong

    Access lifecycleOwner before view attached would be wrong

    I try to access lifecycle in my VIewHolder before attached. It always returns the one from line A even when it goes to line B after attached. The lifecycle owned by user class can not get any life state event

    val View.lifecycleOwner: LifecycleOwner
        get() = getTag(R.id.view_lifecycle_owner) as? LifecycleOwner ?: object : LifecycleOwner,
            LifecycleEventObserver {
        private var lifecycle = LifecycleRegistry(this) -----------------------------> A 
    
            init {
                doOnAttach {
                    if(lifecycle.currentState == Lifecycle.State.DESTROYED) {
                        lifecycle = LifecycleRegistry(this) -----------------------------> B
                    }
                    lifecycle.currentState = Lifecycle.State.CREATED
                    findViewTreeLifecycleOwner()?.lifecycle?.let { viewTreeLifecycle->
                        viewTreeLifecycle.addObserver(this)
                        if(lifecycle.currentState != viewTreeLifecycle.currentState) {
                            lifecycle.currentState = viewTreeLifecycle.currentState
                        }
                    }
                }
                doOnDetach {
                    findViewTreeLifecycleOwner()?.lifecycle?.removeObserver(this)
                    if(lifecycle.currentState != Lifecycle.State.DESTROYED) {
                        lifecycle.currentState = Lifecycle.State.DESTROYED
                    }
                }
            }
    
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                lifecycle.currentState = event.targetState
            }
    
            override fun getLifecycle(): Lifecycle {
                return lifecycle
            }
        }.also {
            setTag(R.id.view_lifecycle_owner, it)
        }
    
    opened by yabee5566 2
Releases(1.0.5)
Owner
Thomas Gorisse
Senior Android/XR Engineer @ DigitalMate
Thomas Gorisse
😴 Lazy and fluent syntactic sugar of Kotlin for initializing Android lifecycle-aware property.

?? Lazy and fluent syntactic sugar of Kotlin for initializing Android lifecycle-aware property.

Jaewoong Eum 347 Dec 9, 2022
Kotlin Multiplatform lifecycle-aware business logic components (aka BLoCs) with routing functionality and pluggable UI (Jetpack Compose, SwiftUI, JS React, etc.), inspired by Badoos RIBs fork of the Uber RIBs framework

Decompose Please see the project website for documentation and APIs. Decompose is a Kotlin Multiplatform library for breaking down your code into life

Arkadii Ivanov 819 Dec 29, 2022
This is an implementation of the Fragment Lifecycle CodeLabs.

AndroidTriviaNavigation - solution code This app is the solution code for Android Kotlin Fundamentals codelab 3.2: Define navigation paths. The app is

Emmanuel Muturia 0 Oct 31, 2021
LifecycleAwareGitHubSearch - The Activity Lifecycle and the ViewModel Architecture

Lifecycle-Aware GitHub Search In this project, we'll modify our GitHub search ap

null 1 Feb 8, 2022
Common Android/Kotlin extensions

Common Android/Kotlin extensions Gradle implementation "com.github.javokhirsavriev:common-extensions:1.0.1" License Copyright 2022 Javokhir Savriev L

Javokhir 0 Feb 15, 2022
A collection of hand-crafted extensions for your Kotlin projects.

Splitties Splitties is a collection of small Kotlin multiplatform libraries (with Android as first target). These libraries are intended to reduce the

Louis CAD 2.2k Dec 25, 2022
Various experimental proposals and extensions to Javalin 4.x used in Reposilite 3.x

Javalin RFCs Various experimental extensions to Javalin 4.x used in Reposilite 3.x. Provides basic support for Kotlin coroutines and async routes with

Reposilite Playground 5 Feb 22, 2022
Automatic CoroutineDispatcher injection and extensions for kotlinx.coroutines

Dispatch Utilities for kotlinx.coroutines which make them type-safe, easier to test, and more expressive. Use the predefined types and factories or de

Rick Busarow 132 Dec 9, 2022
Actions are things that run, with parameters. Serves as a common dependency for a variety of Cepi extensions.

Actions Actions that take in customizable paramaters, an optional target, and do things. Installation Download the jar from Releases OR compile it you

Cepi 1 Jan 9, 2022
Blinking-image-view - A variant of Android View that blinks only the source image (not the background)

Blinker View for Android What is this? Blinker View is an Android View that blinks a given drawable. Yes, it's that simple. Place it in your layout an

Milos Marinkovic 4 Jul 29, 2020