Skip to content

Instantly share code, notes, and snippets.

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
// 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",, "email", "basic") }
.map { profile -> }
// 1) Check if we have the users profile
val existingProfile = profileRepository.findByNameAndValue("primary_email", email).subscribeOn(
.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