问题很简单,我如何将redux-observable与EventSource一起使用?
与RxJs一样:
const observable = Observable.create(observer => {
const eventSource = new EventSource('/model-observable');
return () => {
eventSource.close();
};
});
observable.subscribe({
next: data => {
this.zone.run(() => this.someStrings.push(data));
},
error: err => console.error('something wrong occurred: ' + err)
});
答案 0 :(得分:4)
这听起来更像是关于如何连接到EventSource的一般RxJS问题。这可以通过多种方式完成。如果您关心的只是消息(而不是错误/打开):
import requests
import time
def ColorRequest():
url = 'http://csgoroll.com/v1/roulette/state?token=bcb7841fe779ac0ae2a9e4f882ed3961ce0d714215fede3c025a24fc418e123dcb5a0a47a0ba1825225c14b39e08ea399422eb2b012689a79c41f42b529640e37d5374125c3fef409b2d165c223923dbc27f320c53bf10e46e701058251c97b9' # Could add a + pls str(pagesomething) to add on to the url so that it would update
sourcecode = requests.get(url) # requests the data from the site
obj = sourcecode.json()
for roll in obj['rolls']:
print(roll['id'], roll['roll'])
if __name__ == '__main__':
while True:
ColorRequest()
time.sleep(1000) # these are seconds, ~17min
如果您关心开放和/或错误,则需要更多代码来管理所有内容:
import { fromEvent } from 'rxjs/observable/fromEvent';
const fromEventSource = url => {
return new Observable(observer => {
const source = new EventSource(url);
const message$ = fromEvent(source, 'message');
const subscription = message$.subscribe(observer);
return () => {
subscription.unsubscribe();
source.close();
};
});
};
redux-observable中的用法将是这样的:
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
const fromEventSource = (url, openObserver) => {
return new Observable(observer => {
const open = new Subscriber(openObserver);
const source = new EventSource(url);
const onOpen = event => {
open.next(event);
open.complete();
};
const onError = event => {
if (event.readyState === EventSource.CLOSED) {
observer.complete();
} else {
observer.error(event);
}
};
const onMessage = event => {
observer.next(event.data);
};
source.addEventListener('open', onOpen, false);
source.addEventListener('error', onError, false);
source.addEventListener('message', onMessage, false);
return () => {
source.removeEventListener('open', onOpen, false);
source.removeEventListener('error', onError, false);
source.removeEventListener('message', onMessage, false);
source.close();
};
});
};
fromEventSource('http://some-url.com')
.subscribe(value => console.log(value));