Hello @Junmil_Rey_So, welcome to the community.
The API method collection.createIndex returns a org.reactivestreams.Publisher.
As such the collection#createIndex
doesn’t create the index until the returned publisher’s subscribe()
method is invoked. The subscribe
method takes a org.reactivestreams.Subscriber as a parameter, an interface to be implemented. The implemented methods complete the task of creation of the index when the subscribe
method is invoked.
Publisher<String> indexPublisher = collection.createIndex(Indexes.ascending("dateCreated"));
// The subscribe method requests the publisher to start the stream of data.
indexPublisher.subscribe(new Subscriber<String>() {
public void onSubscribe(Subscription s) {
// Data will start flowing only when this method is invoked.
// The number 1 indicates the number of elements to be received.
s.request(1);
}
public void onNext(String s) {
System.out.println("Index created: " + s); // this will be the new index name
}
public void onError(Throwable t) {
System.out.println("Failed: " + t.getMessage());
}
public void onComplete() {
System.out.println("Completed");
}
});
// This is used to block the main thread until the subscribed task completes asynchronously.
try {
Thread.sleep(3000);
}
catch(InterruptedException e) {
}
You can try using one of the Java implementations at ReactiveX (like RxJava), instead of the low level API from Reactive Streams.