RxSwift.Lifecycle

Once in a while I’m reminded that good API design is of vital importance. Today was such a day. Everybody developing for either Android or iOS platforms knows that one often needs to run something when the view is loaded or when it will appear. Both platforms provide nifty ‘callbacks’ for this:

Android vs iOS lifecycle diagram; iOS: viewDidLoad, viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear, viewDidUnload; Android: onCreate, onStart, onResume, onPause, onStop, onDestroy

It is good practice to start listeners onStart and cleaning up onStop (or other equal pairs). This is all good, and if we want to share functionality we simply create a subclass of UIViewController or Activity and we put the shared logic there. Then comes along another – very unrelated – piece of shared functionality which we also need to put in there: oops! We have only single inheritance. Or, we want that same functionality in both Activity and Fragment, or UIViewController and UITableViewController. There are two problems:

  • We can not override the same method multiple times (without creating a dependency chain).
  • We can not put the logic in 1 shared subclass if there are multiple parents (possibly related by inheritance), since we must create subclasses per specific parent.

Essentially there are some options to workaround this:

  1. Wait until Apple and Google add lifecycle events. That way we can create our own listeners or delegates.
  2. Create shared managers/utilties which we then delegate the logic to with 1 single call in 1 subclass per parent type.
  3. Swallow our pride and create a whole chain of subclasses per root type and per functionality. This becomes nasty very quickly.
  4. Change the compiled or byte code of the top most parent type. By adding lifecycle events we are essentially doing point 1 ourselves.

From how above list is formatted and the title of the article you can guess my preference.

Intermezzo: RxSwift
Since I use Rx (Reactive Extensions) a lot I found I had the following pattern quite often:

var disposable: Disposable? = nil
func viewDidLoad() {
  disposable = getSomeNiceObservable()
    .map(someTransformation)
    .subscribeNext { print($0) }
}
func viewDidUnload() {
  disposable?.dispose()
}

The same holds for Android. Luckily RxSwift adds a rx_deallocated Observable to NSObject which emits a value and completes in deinit. Now above code could be written like this:

func viewDidLoad() {
  _ = getSomeNiceObservable()
    .map(someTransformation)
    .takeUntil(rx_deallocated)
    .subscribeNext { print($0) }
}

Much shorter, and no extra instance variables needed, Eureka!

But this only works for deallocation, and as we are humans, we leak memory. If we retain self in the Observable sequence (this is quite common to accidentally do) a retain cycle is created between the Observable and self, the NSObject. To help and not hinder the programmer, it would be much easier if we could cleanup if the view is dismissed!

Introducing RxLifecycle
I created RxLifecycle, which works much like how RxSwift creates rx_deallocated. It provides 6 new Observables. Using a process called swizzling we swap the methods that correspond to the lifecycle with our own methods which trigger a Rx.Subject which is exposed by a normal field in a Swift extension. This way two Observable<Bool> are exposed:

  • rx_visible: did the controller appear/disappear?
  • rx_willBeVisible: will the controller appear/disappear?

Those are then conveniently split into Observable<Void> per distinct event:

  • rx_willAppear
  • rx_willDisappear
  • rx_appear
  • rx_disappear

Example usage:

Observable.interval(10, scheduler: MainScheduler.instance)
  .takeUntil(self.rx_disappear)
  .subscribeNext { print("\($0)") }

Find the full source at https://gist.github.com/hermanbanken/4ac458aede6290b59a4acd5d52b81a6f.

Building ice/speed skating timing system

One of my projects is building my own timing system for speed skating. I have some ideas of how to build this, but to be sure of the feasibility and needed components I decided to ask some help on reddit/arduino. It is a good description of the project too:


In ice skating and speed skating they employ Photoelectric Retroreflective Sensors (lasers) to time passing over the start/finish line. As a hobbyist ice/speed skater I want to build such a system so we can organise competitions with our club, and time results precisely. By convention the results are published with hundreds/thousands of a second precision. I want to achieve at least that precision, probably a factor higher to be sure. I’m looking for some help/guidance building this as I have not completed many circuit builds…

I have learned that lasers with large range are expensive. Looking at SICK’s WL12L series at the moment. They are available with a range of 18m for ~100 euros/dollars on Ebay. This component would be by far the most expensive component of course. I’m looking to build the rest using off the shelf/hobbyist electronics. Example picture of sensor workings:

Retroreflective Sensor

As multiple skaters can ride in series (are on the same track) the output of the system should be a stream of high precision timestamps (relative to some epoch, preferably sync-able by a shared button to both start + finish units). Would need 2 sensors, one per unit: 1 finish line, 1 start line (rolling start).

I’m wondering if the internal clock of Arduino’s is sufficiently accurate for timing. There may be some time drift, but a match takes ample minutes, not days. I’m considering making the timing more accurate using a RTC. Question: does that adjust the clock, say, every second, or does it also increase precision on a sub-second level? Another approach would be using a oscillator with a binary counter IC, but that requires more setup than just using the Arduino. Would it be (measurably) worth it? I’ve drawn a simplified circuit with oscillator:

timer-circuit

To be ultra portable I want the system to operate over wifi. The operator would use an tablet/iPad to view the results / control the match. Before the match the units could be synced using a coupling button, which would reset the counter IC’s / Arduino in-memory time offset. To transmit the signal I’m thinking about using ESP8266’s (or devices with more powerful antenna) to transmit the stream of times to the central unit. I believe I must use separate boards for the timing chip and the wifi chip, as to not disturb measurements when the WiFi chip is busy sending data. Is that correct? Or would sending data not influence interrupts / timing if using a single ESP instead of Arduino?

TLDR:
– is precision of timing on Arduino enough for 100/1000 of a second precise timing? Considering drift over span of 2/3 hours.
– does sending data over WiFi disturbs interrupt / timing accuracy?
– if so, could this be solved by using 2 distinct chips (communicating over I2C for example) 1 for timing, 1 for WiFi?
– any more tips/hints?

Floating point precision, in practice

Normally as a programmer Float’s are more than precise enough. During one of my projects however I had some serious headaches because of it. At start of the project I was rolling my own points in 3D-space, just a fancy wrapper around 3 Doubles. When I needed more vector powers (cross products, quaternations, rotation matrices) I switched to com.github.jpbetz.subspace.Vector3 from https://github.com/jpbetz/subspace. This Vector3 uses 3 Floats internally, which was fine, cause it wouldn’t make that much of a difference, I thought.

The project I’m working on includes fitting some points to a predefined shape (a inline skate track to be precise). I was calculating the center of the GPS input like this:

val vs: Seq[Vector3] = /* about 3600 points */ ???
val center = vs.reduce(_ + _) / vs.size

Using this center I plotted a blue ‘perfect’ track and my input points in green. The result:
GPX points wrongly centered

As you can see there is some offset between the green and the blue tracks. The orientation is different too, but first I wanted to fix the positioning problem. After many hours of thinkering and continuing with other issues, I came across another issue with my Floats: the formatting back to GPS longitude and latitudes. For some reason I wrongly typed the formatting string, but due to this issue my attention shifted to floating point precision and it’s quirks. Then I wrote this little test:

val sum_d = vs
  .map(v => (v.x.toDouble, v.y.toDouble, v.z.toDouble))
  .reduce((a,b) => (a._1+b._1, a._2+b._2, a._3+b._3))
val center_d = Vector3(
  (sum_d._1/vs.size).toFloat,
  (sum_d._2/vs.size).toFloat,
  (sum_d._3/vs.size)).toFloat
)
var center = vs.reduce(_ + _) / vs.size
println(s"Center: $center")
println(s"Center using doubles: $center_d")
println(s"Diff: ${center - center_d}")

which printed

Center: (3912099.2, 301133.1, 5028436.0)
Center using doubles: (3912057.8, 301132.88, 5028494.5)
Diff = (41.5, 0.21875, -58.5)

Tada! Issue found. Adding all those large numbers (vectors relative to the earths center) caused the precision of the resulting float to be too little to accomodate for the large numbers plus their precision. Using doubles to store the accumulating numbers results in a better center, which produces the following image:

GPX points correctly centered

Much better! So remember, floats are not always good enough.