Last active
January 7, 2016 17:01
-
-
Save michaelst0/40a4758aadf9f92d9185 to your computer and use it in GitHub Desktop.
Async Reactive operation with fallback observable
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
//...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