我遇到了Flowable< T>的奇怪问题。 vs Observable< T>在rxjava中(io.reactivex.rxjava2 - v2.0.8)。这里我的代码如下所示,其中 map(...)。subscribe(...)函数未被调用/执行。
flowable.flatMap(...return new flowable...).map(...).subscribe(...)
令人惊讶的是,如果我翻转我的代码以使用Observable< T>而不是Flowable< T>,按照预期调用/执行 map(...)。subscribe(...)。我可能会遗漏一些简单的东西,让我知道它可能是什么?
谢谢
`
public class Application {
public static void main(String[] args) {
// Note: Working; get the list of databases
DatabaseFlowable databases = new DatabaseFlowable(sourceClient);
// Note: Working; for each database get the list of collections in it
Flowable<Resource> resources = databases
.flatMap(db -> {
logger.info(" ==> found database {}", db.getString("name"));
return new CollectionFlowable(sourceClient, db.getString("name"));
// Note: Working; CollectionFlowable::subscribeActual works as well
});
resources
.map(resource -> {
// Note: Nothing in here gets executed
logger.info(" ====> found resource {}", resource.toString());
return resource;
})
.subscribe(m -> {
// Note: Nothing in here gets executed
logger.info(m.toString());
});
}
}
public class DatabaseFlowable extends Flowable<Document> {
private final static Logger logger = LoggerFactory.getLogger(DatabaseFlowable.class);
private final MongoClient client;
public DatabaseFlowable(MongoClient client) {
this.client = client;
}
@Override
protected void subscribeActual(Subscriber<? super Document> subscriber) {
ListDatabasesIterable<Document> cursor = client.listDatabases();
MongoCursor<Document> iterator = cursor.iterator();
while(iterator.hasNext()) {
Document item = iterator.next();
if (!item.isEmpty()) {
String message = String.format(" found database name: %s, sizeOnDisk: %s",
item.getString("name"), item.get("sizeOnDisk"));
logger.info(message);
subscriber.onNext(item);
}
}
subscriber.onComplete();
}
}
public class CollectionFlowable extends Flowable<Resource> {
private final static Logger logger = LoggerFactory.getLogger(CollectionFlowable.class);
private final MongoClient client;
private final String databaseName;
public CollectionFlowable(MongoClient client, String databaseName) {
this.databaseName = databaseName;
this.client = client;
}
@Override
protected void subscribeActual(Subscriber<? super Resource> subscriber) {
MongoDatabase database = client.getDatabase(databaseName);
ListCollectionsIterable<Document> cursor = database.listCollections();
MongoCursor<Document> iterator = cursor.iterator();
while(iterator.hasNext()) {
Document item = iterator.next();
if (!item.isEmpty()) {
logger.info(" ... found collection: {}.{}", database.getName(), item.getString("name"));
Resource resource = new Resource(databaseName,
item.getString("name"),
(Document) item.get("options"));
subscriber.onNext(resource);
}
}
subscriber.onComplete();
}
}
`
答案 0 :(得分:0)
这是因为您没有正确遵循Flowable
协议。没有对subscriber.onSubscribe(...)
的调用,也没有遵守subscriber.request(...)
强加的限制。
由于您的实施绝不会观察背压,因此请使用Flowable.create
创建一个缓冲版本,将您的实施移至Observable
,而不是背压。
您看到的行为的原因是下游观察者没有请求任何项目,因此您对onNext
的调用将被丢弃。