RxPY - Operadores Conectáveis

publicar

Este método converterá o observável em um observável conectável.

Sintaxe

publish(mapper=None)

Parâmetros

mapeador: opcional. Uma função usada para multicast de valores de origem várias vezes, sem ter que fazer várias assinaturas.

Exemplo

from rx import create, range, operators as op
import random
def test_observable(observer, scheduler):
   observer.on_next(random.random())
   observer.on_completed()
source = create(test_observable).pipe(op.publish())
test1 = source.subscribe(on_next = lambda i: print("From subscriber 1 - {0}".format(i)))
test2 = source.subscribe(on_next = lambda i: print("From subscriber 2 –
{0}".format(i)))
source.connect()

Resultado

E:\pyrx>python testrx.py
From subscriber 1 - 0.14751607273318490
From subscriber 2 - 0.1475160727331849

ref_count

Este operador tornará o observável um observável normal.

Sintaxe

ref_count()

Exemplo

from rx import create, operators as op
import random
def test_observable(observer, scheduler):
   observer.on_next(random.random())
source = create(test_observable).pipe(op.publish(),op.ref_count())
test1 = source.subscribe(on_next = lambda i: print("From subscriber 1 - {0}".format(i)))
test2 = source.subscribe(on_next = lambda i: print("From subscriber 2 - {0}".format(i)))

Resultado

E:\pyrx>python testrx.py
From subscriber 1 - 0.8230640432381131

repetir

Este método funciona de forma semelhante ao replaySubject. Este método retornará os mesmos valores, mesmo se o observável já tiver emitido e alguns dos assinantes estiverem atrasados ​​na assinatura.

Sintaxe

replay()

Exemplo

from rx import create, range, operators as op
import random
from threading import Timer
def test_observable(observer, scheduler):
   observer.on_next(random.random())
   observer.on_completed()
source = create(test_observable).pipe(op.replay())
test1 = source.subscribe(on_next = lambda i: print("From subscriber 1 - {0}".format(i)))
test2 = source.subscribe(on_next = lambda i: print("From subscriber 2 - {0}".format(i)))
source.connect()
print("subscriber called after delay ")
def last_subscriber():
   test3 = source.subscribe(on_next = lambda i: print("From subscriber 3 - {0}".format(i)))
t = Timer(5.0, last_subscriber)
t.start()

Resultado

E:\pyrx>python testrx.py
From subscriber 1 - 0.8340998157725388
From subscriber 2 - 0.8340998157725388
subscriber called after delay
From subscriber 3 - 0.8340998157725388