Skip to content

Instantly share code, notes, and snippets.

@kaeawc
Created October 2, 2018 03:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaeawc/ae65aee98c416b71d9e37c70a40ac9a1 to your computer and use it in GitHub Desktop.
Save kaeawc/ae65aee98c416b71d9e37c70a40ac9a1 to your computer and use it in GitHub Desktop.
Diposer implementation
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import java.util.concurrent.TimeUnit
class LaunchActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_launch)
}
override fun onResume() {
super.onResume()
Timber.i("create single")
Flowable.range(0, 10_000)
.delay(100, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.subscribe({
Timber.i("counted $it")
}, {})
.dispose(Lifecycle.Event.ON_PAUSE)
}
fun Disposable.dispose(filter: Lifecycle.Event) {
lifecycle.addObserver(Disposer(this, filter))
}
@Suppress("UNUSED", "UNUSED_PARAMETER")
open class Disposer(
private val disposable: Disposable,
private val filter: Lifecycle.Event): LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onAny(source: LifecycleOwner, event: Lifecycle.Event) {
if (event != filter) return
if (!disposable.isDisposed) disposable.dispose()
Timber.i("disposed")
}
}
}
@sellmair
Copy link

sellmair commented Oct 2, 2018

That is what I am talking about! 26 LOC implementation ☺️ 👍

@sellmair
Copy link

sellmair commented Oct 2, 2018

Maybe you might want to remove the Disposer from the lifecycle with removeObserver once the internal Disposable is disposed, because then the Disposer is not needed anymore 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment