loco - launch on π cancel on π₯
You can now use the native Lifecycle.repeatOnLifecycle
repositories {
jcenter()
}
dependencies {
implementation("at.florianschuster.loco:loco-core:$version")
}
extensions to launch on a specific lifecycle event & cancel on a specific lifecycle event
example:
val lifecycle: Lifecycle
lifecycle.launchOnCreateCancelOnDestroy {
/**
* these will be launched once the lifecycle is created and cancelled once the
* lifecycle is destroyed. it is also relaunched on each create.
*/
someFlow().launchIn(this)
launch { someSuspendingFunction() }
}
example:
class MainActivity : Activity(R.layout.activity_main) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
launchOnLifecycleCreateCancelOnLifecycleDestroy {
/**
* this will be launched once the Activity is created and cancelled once the
* activity is destroyed. it is also relaunched on each create.
*/
button.clicks().onEach {
// do something
}.launchIn(this)
}
}
}
example:
class SomeFragment : Frgment(R.layout.fragment_some) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
launchOnViewLifecycleStartCancelOnViewLifecycleStop {
/**
* this will be launched once the fragment view lifecycle is started and cancelled
* once the fragment view lifecycle is stopped. it is also relaunched on each start.
*/
button.clicks().onEach {
// do something
}.launchIn(this)
}
}
}
example view attach/detach:
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
init {
launchOnViewAttachCancelOnViewDetach {
/**
* this will be launched once the view is attached to a window and cancelled
* once the view is detached from the window. it is also relaunched in each
* attach to window.
*/
someFlow().launchIn(this)
launch { suspendingFunction() }
}
}
}
example view-tree-lifecycle:
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
override fun onAttachedToWindow() {
super.onAttachedToWindow()
launchOnLifecycleResumeCancelOnLifecyclePause {
/**
* this will be launched once the view tree lifecycle is resumed and cancelled
* once the view tree lifecycle is paused. it is also relaunched on each resume.
*/
someFlow().launchIn(this)
launch { suspendingFunction() }
}
}
}
visit my website.