Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.