Search code examples
javalambdafunctional-programmingreactive-programmingproject-reactor

Return a String value when method return type is Mono<String>


My method returns a Mono<String> response back to the controller. However, I am getting the following error while trying to return a String value.

Required Type: Mono<String>, 
Provided: Mono<Object>
no instance(s) of type variable(s) T exist so that Mono<T> conforms to String inference variable R has incompatible bounds: equality constraints

Service:

public Mono<String> moveToDB(String pid, String op, MoveRequest moveRequest) {
        return Mono.just(pid)
                .subscribeOn(Schedulers.boundedElastic())
                .map(id -> persistenceService.withTransaction((s, em) -> {
                     //some code goes here
                    if (condition)
                       return "data sync failed"; //ERROR
                    return "data synced successfully"; //ERROR
        }));
}

I am new to reactive programming and I am probably making a silly mistake but I'd appreciate some help on this. Thanks!


Solution

  • I guess method withTransaction() does not return String as it should. You should map the return value to a String:

    .map(id -> service.withTransaction((s, em) -> {
        //some code goes here
        if (true)
            return "data sync failed";
        return "data synced successfully";
    }))
    .map(e -> e.toString()); //or whatever