Last active
September 11, 2017 11:59
-
-
Save ruigoncalo/c8a504d8724f6635df17b9e99cf5d181 to your computer and use it in GitHub Desktop.
Spek with Subjects - Presenter
This file contains 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
class DistancesPresenter @Inject constructor(private val roundInteractor: RoundInteractor) { | |
private val subscriptions by lazy { CompositeSubscription() } | |
private lateinit var view: View | |
fun attachView(view: View) { | |
this.view = view | |
} | |
fun start() { | |
subscriptions.add( | |
Observable.combineLatest( | |
roundInteractor.changeHoleEvents(), | |
roundInteractor.distanceUnitEvents(), | |
roundInteractor.distancesEvents(), | |
{ hole: Hole, distanceUnit: DistanceUnit, distances: List<RoundDistances> -> | |
val isMetricDistanceUnit = distanceUnit == DistanceUnit.METRIC | |
val distancesToGreen = distances[hole.sequence - 1].let { | |
holeDistances -> if (isMetricDistanceUnit) { | |
holeDistances | |
} else { | |
toImperial(holeDistances) | |
} | |
} | |
Pair(distancesToGreen, isMetricDistanceUnit) | |
}) | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe(object : DefaultSubscriber<Pair<RoundDistances, Boolean>>() { | |
override fun onNext(distances: Pair<RoundDistances, Boolean>) { | |
view.displayDistancesToGreen( | |
distances.first.greenBackDistance.toString(), | |
distances.first.greenCenterDistance.toString(), | |
distances.first.greenFrontDistance.toString()) | |
view.displayDistanceUnit(distances.second) | |
} | |
override fun onError(e: Throwable) { | |
// handle error | |
} | |
}) | |
) | |
} | |
fun stop() { | |
subscriptions.clear() | |
} | |
private fun toImperial(distances: RoundDistances) = | |
RoundDistances(toYards(distance.back), toYards(distances.center), toYards(distances.front)) | |
private fun toYards(meters: Int) = Math.round(meters * 1.0936) | |
interface View { | |
fun displayDistancesToGreen(distanceToGreenBack: String, distanceToGreenCenter: String, distanceToGreenFront: String) | |
fun displayDistanceUnit(isMetricDistanceUnit: Boolean) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment