Search code examples
javarx-java2vert.x

incompatible types: Single<HttpServer> cannot be converted to Completable


I am trying to use RxJava2 in Vert.x within a verticle:

import io.reactivex.Completable;
import io.vertx.core.Promise;

public class MainVerticle extends io.vertx.reactivex.core.AbstractVerticle {


  @Override
  public Completable rxStart() {
    return vertx.createHttpServer().requestHandler(req -> {
      req.response()
        .putHeader("content-type", "text/plain")
        .end("Hello from Vert.x!");
    })
      .rxListen(8080);

  }
}

The compile complains:

 error: incompatible types: Single<HttpServer> cannot be converted to Completable
      .rxListen(8080);
               ^
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.

I do not know, which method I should call.


Solution

  • Single<HttpServer> rxListen(int port,String host)
    

    returns an instance of Single not Completable from the question is not clear what you're trying to do but if you want to listen on a port you need to do something like this

    public class MyVerticle extends AbstractVerticle {
    
     private HttpServer server;
    
     public void start(Future<Void> startFuture) {
       server = vertx.createHttpServer().requestHandler(req -> {
         req.response()
           .putHeader("content-type", "text/plain")
           .end("Hello from Vert.x!");
         });
    
       // Now bind the server:
       server.listen(8080, res -> {
         if (res.succeeded()) {
           startFuture.complete();
         } else {
           startFuture.fail(res.cause());
         }
       });
     }
    }
    

    if you want to work with Completable you need to subscribe to the server and call the method rxClose

     Completable single = server.rxClose();
    
        // Subscribe to bind the server
        single.
          subscribe(
            () -> {
              // Server is closed
            },
            failure -> {
              // Server closed but encoutered issue
            }
          );