MOLO17 / couchbase-lite-kotlin

Kotlin-friendly extensions for Couchbase Lite Android and Java SDKs.
Apache License 2.0
15 stars 4 forks source link

Better Lifecycle Code #2

Open VincentJoshuaET opened 3 years ago

VincentJoshuaET commented 3 years ago

This doesn't need Lifecycle.Event.ON_DESTROY -> source.lifecycle.removeObserver(this) anymore.

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.couchbase.lite.Replicator

class ReplicatorLifecycleObserver(private val replicator: Replicator) : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun start() = replicator.start()

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun stop() = replicator.stop()

}

fun Replicator.bindToLifecycle(lifecycle: Lifecycle) {
    lifecycle.addObserver(ReplicatorLifecycleObserver(this))
}
jeffdgr8 commented 1 year ago

@VincentJoshuaET LifecycleObserver documentation now says "Don't use this interface directly. Instead implement either DefaultLifecycleObserver or LifecycleEventObserver to be notified about lifecycle events."

OnLifecycleEvent is deprecated and gives additional details for this: "This annotation required the usage of code generation or reflection, which should be avoided. Use DefaultLifecycleObserver or LifecycleEventObserver instead."

VincentJoshuaET commented 1 year ago

I submitted this in 2020. Here is the updated code:

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.couchbase.lite.Replicator

class ReplicatorLifecycleObserver(private val replicator: Replicator) : DefaultLifecycleObserver {
    override fun onStart(owner: LifecycleOwner) {
        replicator.start()
    }

    override fun onStop(owner: LifecycleOwner) {
        replicator.stop()
    }
}

fun Replicator.bindToLifecycle(lifecycle: Lifecycle) {
    lifecycle.addObserver(ReplicatorLifecycleObserver(this))
}

fun Replicator.bindToLifecycle(lifecycleOwner: LifecycleOwner) {
    lifecycleOwner.lifecycle.addObserver(ReplicatorLifecycleObserver(this))
}