This is in Kotlin, but I think anyone who writes Java will be able to understand.
I'm trying to make a stopwatch with Rx and I'm having a little trouble with doing the actual stopping and starting. The big problem is that I don't know how to keep the current time, while modifying it as different actions (starting and stopping) come in. Here's what I've got right now.
fullTime.switchMap { startTime ->
controlCommands.switchMap { command ->
when (command) {
ControlState.PLAY -> Observable.interval(1L, TimeUnit.SECONDS).map {
ControlState.PLAY
}
ControlState.PAUSE -> Observable.just(ControlState.PAUSE)
else -> Observable.just(ControlState.STOP)
}
}
}
Where fullTime
and controlCommands
are Observable
s that emit events about the current starting time to count down from and say what to do next, respectively. I want to chain off of controlCommands
and be able to keep state starting at startTime
that will count down when a PLAY
event appears, pause when PAUSE
appears, and reset at startTime
when STOP
appears.
scan
almost works, but I don't know how to stop after the timer hits 0 and PLAY
is still being sent every second, since it would be sending duplicate info. Also it doesn't allow a separation between the state and the observed value. So the value I accumulate with scan
has to be the same type as the value inside the Observable
(if that makes sense).
Any ideas what I should do?