我是RxJava的新手,我试图创建一个函数来返回一个从AMQP队列接收消息的观察者,我需要确保与服务器的连接和创建了队列,这就是我所拥有的:
public Observable<String> consume(String queueName) {
Observable<String> consume = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> sub) {
try {
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
sub.onNext(message);
// sub.onCompleted();
}
};
channel.basicConsume(queueName, true, consumer);
} catch (IOException e) {
sub.onError(e);
}
}
});
return Observable.zip(connect(), queueDeclare(queueName), consume, (conn, queue, consumer) -> {
return consumer;
});
}
}
server.consume(QUEUE_NAME).subscribe(c -> {
System.out.println("Received " + c);
}
这有效,它连接到服务器,创建队列并创建使用者,并在消息到达时写入。问题是它只能在第一次工作,因为订阅是在&#34; zip&#34;不是消费对象,下一个消息到达下一个呼叫,但不激活用户。
我使用了以下方法:
connectionObserver.subscribe(conn->{
queueObserver.subscribe(queue->{
consumeObserver.subscribe(message->{
System.out.println("Received " + message);
});
});
});
但我想认为这是更好的方法,特别是因为我想创建一个功能来实现这一目标
提前致谢
编辑:
这也有效,而且更清洁:
public Observable<String> consume(String queueName) {
return connect().flatMap(conn -> {
return queueDeclare(queueName);
}).flatMap(queue -> {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> sub) {
try {
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
sub.onNext(message);
// sub.onCompleted();
}
};
channel.basicConsume(queueName, true, consumer);
} catch (IOException e) {
sub.onError(e);
}
}
});
});
}
}
仍然愿意接受想法