Como converter RX Observable em Play Enumerator
-
21-12-2019 - |
Pergunta
Configurei com sucesso um websocket no Play usando sua construção Enumerator nativa, chamando algum código que retorna uma String:
def operationStatusFeed = WebSocket.using[String] { implicit request =>
val in = Iteratee.ignore[String]
val out = Enumerator.repeatM {
Promise.timeout(operation, 3 seconds)
}
(in, out)
}
Agora eu quero o meu operation
função para retornar um rx.lang.scala.Observable[String]
em vez de uma String, e quero gerar qualquer String assim que ela entrar.Como posso mapear este Observável para um play.api.libs.iteratee.Enumerator
?
Solução
Você pode usar a conversão implícita de Bryan Gilbert.Isso funcionará perfeitamente, mas tome cuidado ao usar o versão atualizada das conversões de Bryan Gilbert !O cancelamento da assinatura nunca é solicitado na resposta de Jeroen Kransen (e isso é ruim!).
/*
* Observable to Enumerator
*/
implicit def observable2Enumerator[T](obs: Observable[T]): Enumerator[T] = {
// unicast create a channel where you can push data and returns an Enumerator
Concurrent.unicast { channel =>
val subscription = obs.subscribe(new ChannelObserver(channel))
val onComplete = { () => subscription.unsubscribe }
val onError = { (_: String, _: Input[T]) => subscription.unsubscribe }
(onComplete, onError)
}
}
class ChannelObserver[T](channel: Channel[T]) extends rx.lang.scala.Observer[T] {
override def onNext(elem: T): Unit = channel.push(elem)
override def onCompleted(): Unit = channel.end()
override def onError(e: Throwable): Unit = channel.end(e)
}
Para completar, aqui está a conversão de Enumerator para Observable :
/*
* Enumerator to Observable
*/
implicit def enumerator2Observable[T](enum: Enumerator[T]): Observable[T] = {
// creating the Observable that we return
Observable({ observer: Observer[T] =>
// keeping a way to unsubscribe from the observable
var cancelled = false
// enumerator input is tested with this predicate
// once cancelled is set to true, the enumerator will stop producing data
val cancellableEnum = enum through Enumeratee.breakE[T](_ => cancelled)
// applying iteratee on producer, passing data to the observable
cancellableEnum (
Iteratee.foreach(observer.onNext(_))
).onComplete { // passing completion or error to the observable
case Success(_) => observer.onCompleted()
case Failure(e) => observer.onError(e)
}
// unsubscription will change the var to stop the enumerator above via the breakE function
new Subscription { override def unsubscribe() = { cancelled = true } }
})
}
Rx para WebSockets no jogo
Por outro lado, você pode observar que na maior parte do tempo você lida com Iteratees e Enumerators in Play é quando você trabalha com WebSockets (como você faz aqui).Todos concordamos que Iteratees são realmente menos intuitivos que Observables e é provavelmente por isso que você está usando Rx em seu projeto Play.
A partir dessa observação, construí uma biblioteca chamada WidgetManager isso faz exatamente isso:integração do Rx no Play, livrando-se da manipulação dos Iteratees.
Usando essa biblioteca, seu código poderia ser simplesmente:
def operationStatusFeed = WebSocket.using[String] { implicit request =>
// you can optionally give a function to process data from the client (processClientData)
// and a function to execute when connection is closed (onClientClose)
val w = new WidgetManager()
w.addObservable("op", operation)
// subscribe to it and push data in the socket to the client (automatic JS callback called)
w.subscribePush("op")
// deals with Iteratees and Enumerators for you and returns what's needed
w.webSocket
}
A biblioteca está no GitHub aqui: RxPlay (Contribuições são bem-vindas)
Outras dicas
Eu fiz essa solução inspirada em Brian Gilberto:
class ChannelObserver[T](chan: Channel[T]) extends Observer[T] {
override def onNext(arg: T): Unit = chan.push(arg)
override def onCompleted(): Unit = chan.end()
override def onError(e: Throwable): Unit = chan.end(e)
override val asJavaObserver: rx.Observer[T] = new rx.Observer[T] {
def onCompleted() {
chan.end()
}
def onError(e: Throwable) {
chan.end(e)
}
def onNext(arg: T) {
chan.push(arg)
}
}
}
implicit def observable2Enumerator[T](obs: Observable[T]): Enumerator[T] = {
Concurrent.unicast[T](onStart = { chan =>
obs.subscribe(new ChannelObserver(chan))
})
}
A função implícita converte Observáveis em Enumeradores sem qualquer código adicional.