Skip to content

Instantly share code, notes, and snippets.

@edudobay
Last active October 19, 2018 00:24
Show Gist options
  • Save edudobay/102c30ec7be277664ee7e1b5af2d5acc to your computer and use it in GitHub Desktop.
Save edudobay/102c30ec7be277664ee7e1b5af2d5acc to your computer and use it in GitHub Desktop.
Flowable Clock: a Clock that switches its behavior whenever a new item is emitted by a given Flowable
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import org.threeten.bp.Clock
import org.threeten.bp.Instant
import org.threeten.bp.ZoneId
import kotlin.properties.Delegates
/**
* A [Clock] that acts as the latest clock emitted so far by the given Flowable.
*
* It is assumed that the given Flowable will have emitted at least one item before any Clock
* method is called on this instance; if these methods are called before the first emission,
* an [IllegalStateException] will be thrown.
*/
class FlowableClock(clocks: Flowable<Clock>) : Clock(), Disposable {
private var currentClock: Clock by Delegates.notNull()
private val clocks = clocks.replay(1).autoConnect()
private val subscription: Disposable = clocks.subscribe { clock ->
currentClock = clock
}
// Clock
override fun withZone(newZone: ZoneId): Clock =
FlowableClock(clocks.map { it.withZone(newZone) })
override fun getZone(): ZoneId = currentClock.zone
override fun instant(): Instant = currentClock.instant()
// Disposable
override fun isDisposed(): Boolean = subscription.isDisposed
override fun dispose() = subscription.dispose()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment