Skip to content

Instantly share code, notes, and snippets.

@mchlstckl
Last active January 7, 2016 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchlstckl/40a4758aadf9f92d9185 to your computer and use it in GitHub Desktop.
Save mchlstckl/40a4758aadf9f92d9185 to your computer and use it in GitHub Desktop.
Async Reactive operation with fallback observable
//...elided package, class and imports...//
@RequestMapping("/profiles", method = arrayOf(RequestMethod.GET))
fun getUserByEmail(
@RequestParam(value = "email") email: String,
): DeferredResult<ResponseEntity<Profile>> {
val result = DeferredResult<ResponseEntity<Profile>>()
val uriBuilder = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{uuid}")
// Setup the fallback steps for getting the user from the userService,
// creating a new profile, and storing the profile
val newProfile = Observable.defer { userService.fetchUser(email) }
.onError { result.setErrorResult(ResponseEntity.badRequest().build()) }
.map { user -> Profile(UUID.randomUUID(), "primary_email", user.email, "email", "basic") }
.map { profile -> profileRepository.save(profile) }
// 1) Check if we have the users profile
val existingProfile = profileRepository.findByNameAndValue("primary_email", email).subscribeOn(Schedulers.io())
existingProfile
.onErrorResumeNext(newProfile) // 2) We don't have it, so let's get it as newProfile
.map { profile -> createResponseEntity(profile, uriBuilder.buildAndExpand(profile.uuid).toUri()) }
.subscribe { response -> result.setResult(response) }
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment