Created
October 2, 2018 03:56
-
-
Save kaeawc/ae65aee98c416b71d9e37c70a40ac9a1 to your computer and use it in GitHub Desktop.
Diposer implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe you might want to remove the
Disposer
from the lifecycle withremoveObserver
once the internalDisposable
is disposed, because then theDisposer
is not needed anymore 🤔