Image for post
Image for post

Tidy up your Observable Streams with Kotlin’s Sealed Classes

Collin Flynn
Aug 30, 2017 · 3 min read
userService.updateEmail("newEmail@example.com")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<UserInfo>() {
//...
})
Image for post
Image for post
No problem.

The Java Way

onSuccess(Either<UserInfo, EmailUpdateError> result)
if (either.isSuccess()) {
UserInfo userInfo = either.success().get();
// handle success
} else {
EmailUpdateFailure failure = either.failure().get();
// handle failure
}
You could collapse the models down to a more elegant wrapper (other than Pair<>), but the problem remains: nullable fields and manual state checking.

Use Kotlin’s Sealed Classes

The compiler can know for sure that all EmailUpdate objects will be one of these types.
override fun onSuccess(result: EmailUpdate) {
when (result) {
is Success -> publish(result.updatedProfile)
PermissionDenied -> onPermissionDenied()
SignInToContinue -> showSignInDialog()
is EmailInvalid ->
showEmailError(result.input, result.error)
}
}
Image for post
Image for post
Mmmm.

Livefront

Thoughts from the Livefront team

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store