The library I\'m using emits a series of Message
objects using callback object.
interface MessageCallback {
onMessage(Message message);
}
I think you need something like this (example given in scala)
import rx.lang.scala.{Observable, Subscriber}
case class Message(message: String)
trait MessageCallback {
def onMessage(message: Message)
}
object LibraryObject {
def setCallback(callback: MessageCallback): Unit = {
???
}
def removeCallback(callback: MessageCallback): Unit = {
???
}
def start(): Unit = {
???
}
}
def messagesSource: Observable[Message] =
Observable((subscriber: Subscriber[Message]) ⇒ {
val callback = new MessageCallback {
def onMessage(message: Message) {
subscriber.onNext(message)
}
}
LibraryObject.setCallback(callback)
subscriber.add {
LibraryObject.removeCallback(callback)
}
})
As for the blocking/non-blocking start()
: Usually callback-based architecture separates callback subscription and the process start. In that case, you can create as many messageSource
s as you want completely independently of when you start()
the process. Also the decision whether you fork it or not is completely upon you. Is your architecture different from this?
You should also handle finishing the process somehow. The best would be to add an onCompleted
handler to the MessageCallback interface. If you want to handle errors, also add an onError
handler. Now behold, you have just declared the fundamental building stone of RxJava, an Observer :-)
We can convert it to Observable like this (example for RxJava 2):
Observable<Message> source = Observable.create(emitter -> {
MessageCallback callback = message -> emitter.onNext(message);
libraryObject.setCallback(callback);
Schedulers.io().scheduleDirect(libraryObject::start);
emitter.setCancellable(() -> libraryObject.removeCallback(callback));
})
.share(); // make it hot
share
makes this observable hot, i.e. multiple subscribers will share single subscription, i.e. there will be at most one callback registered with libraryObject
.
I used io
scheduler to schedule start
call to be made from background thread, so it does not delay first subscription.
It is quite common scenario as well. Let's say we have the following callback-style asynchronous method:
libraryObject.requestDataAsync(Some parameters, MessageCallback callback);
Then we can convert it to Observable like this (example for RxJava 2):
Observable<Message> makeRequest(parameters) {
return Observable.create(emitter -> {
libraryObject.requestDataAsync(parameters, message -> {
emitter.onNext(message);
emitter.onComplete();
});
});
}