簡體   English   中英

Java Async MongoDB驅動程序和RxJava2 Observables

[英]Java Async MongoDB driver and RxJava2 Observables

我正在研究RxJava2的反應式編程,並且對它在MongoDB等異步數據庫驅動程序中的用法有疑問。

如果我使用阻止MongoDB驅動程序來獲取集合,則方法如下:

public class MyDao{
   ...
   public Document getFirstDocument(String collectionName){
      MongoCollection<Document> collection = database.getCollection(collectionName);
      return collection.find().first();
   }
}



public class MyService {
   ...
   public Observable<Document> getFirstOf(String collectionName){
       return Observable.just(myDao.getFirstDocument(collectionName)); 
   }
}

相反,使用MongoDB的異步驅動程序,我的讀取操作返回類型為void(而不是Document或Future),其內部帶有回調方法,例如:

collection.find().first(
        (document, throwable) -> {
            myService.myCallback(document);
        }
);

因此,如何將可觀察文檔傳遞給MyService?

public class MyDao{
   ...
   public void getFirstDocument(String collectionName){
      MongoCollection<Document> collection = database.getCollection(collectionName);
      collection.find().first(
        (document, throwable) -> {
            //SOME SORT OF CALLBACK
        }
     );
   }
}



public class MyService {
   ...
   public Observable<Document> getFirstOf(String collectionName){
       return ??????? 
   }
}

當您在使用Observable.just()

public Observable<Document> getFirstOf(String collectionName){
    return Observable.just(myDao.getFirstDocument(collectionName)); 
}

它等於下一個代碼

public Observable<Document> getFirstOf(String collectionName){
    Document doc = myDao.getFirstDocument(collectionName);
    return Observable.just(doc); 
}

您會注意到它不是async代碼,並且對DB的請求是在調用線程上執行的。 為了使代碼async您需要像這樣重寫它

public Observable<Document> getFirstOf(String collectionName){
    return Observable.fromCallable(() -> myDao.getFirstDocument(collectionName)); 
}

如果您使用的是async MongoDB驅動程序,並且希望將其包裝在Observable ,則可以用這種方式編寫

public Observable<Document> getFirstDocument(String collectionName) {
    return Observable.create(emitter -> {
        MongoCollection<Document> collection = database.getCollection(collectionName);
        collection.find().first((document, throwable) -> {
            if(document != null) {
                emitter.onNext(document);
                emitter.onComplete();
            } else if(throwable != null) {
                emitter.onError(throwable);
            }
        });
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM