A Extension of Android Lifecycle Management for Kotlin
init {
onStart {
service.start()
}
onResume {
service.refresh()
}
}
add maven url in to your build.gradle (Normally in root project)
repositories {
maven {
url "http://harrytylenol97.bintray.com/maven"
}
}
And add library into module dependencies
compile 'com.tylenol.library:lifecyclin:0.2.1'
First you should define class which inherits LifecycleObserver
class SampleActivity : LifecycleCompatActivity() {
var myListener = MyListener()
// ...
}
// ...
class MyListener : LifecycleObserver { /**/ }
addObserver(myListener) // Method 1
val myListener = MyListener().registerObserver(this) // Method 2
You can also add 2 more Observers as vararg
addObserver(myListener).addObserver(myLocationListener).addObserver(myGoogleApiClientListener)
addObserver(myListener, myLocationListener, myGoogleApiClientListener)
Define Units(functions) to each lifecycle components at once (Automatically Add it as Observer to LifecycleRegistry)
init {
val listener : MyLocationListener
onCreate {
listener = MyLocationListener()
}
onStart {
listener.start()
}
onStop {
listener.stop()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val service = MyService()
onResume {
service.resume()
}
onPause {
service.pause()
}
}
check current lifecycle status and return true if current status is matched
if (isCreated()) { // Do something cooler }
val myViewModel = MyViewModel().asViewModel(this) // 'this' is AppCompatActivity
myViewModel.getUsers().initObserver(this) {
user -> doSomething(user)
}