本文整理汇总了TypeScript中rxjs.Subject.create方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Subject.create方法的具体用法?TypeScript Subject.create怎么用?TypeScript Subject.create使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rxjs.Subject
的用法示例。
在下文中一共展示了Subject.create方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: create
private create(url): WebSocketConnection {
const ws = new WebSocket(url);
const openObservable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
ws.onopen = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
});
const messageObservable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
});
const messageObserver = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
};
return {open: openObservable, messages: Rx.Subject.create(messageObserver, messageObservable)};
}
示例2: fixtureStore
export function fixtureStore(config: JSONObject) {
const dummyNotebook = buildFixtureNotebook(config);
const frontendToShell = new Subject();
const shellToFrontend = new Subject();
const mockShell = Subject.create(frontendToShell, shellToFrontend);
const channels = mockShell;
const kernelRef = createKernelRef();
const contentRef = createContentRef();
const initialAppState: AppState = {
core: makeStateRecord({
kernelRef,
entities: makeEntitiesRecord({
contents: makeContentsRecord({
byRef: Immutable.Map({
[contentRef]: makeNotebookContentRecord({
model: makeDocumentRecord({
notebook: dummyNotebook,
savedNotebook:
config && config.saved === true
? dummyNotebook
: emptyNotebook,
cellPagers: Immutable.Map(),
cellFocused:
config && config.codeCellCount && config.codeCellCount > 1
? dummyNotebook.get("cellOrder", Immutable.List()).get(1)
: null
}),
filepath:
config && config.noFilename ? "" : "dummy-store-nb.ipynb"
})
})
}),
kernels: makeKernelsRecord({
byRef: Immutable.Map({
[kernelRef]: makeRemoteKernelRecord({
channels,
status: "not connected"
})
})
})
})
}),
app: makeAppRecord({
notificationSystem: {
addNotification: () => {} // most of the time you'll want to mock this
},
githubToken: "TOKEN"
}),
config: Immutable.Map({
theme: "light"
}),
comms: makeCommsRecord()
};
return createStore(rootReducer, initialAppState as any);
}
示例3: test
test("errors if the kernel is not connected in create", done => {
const frontendToShell = new Subject();
const shellToFrontend = new Subject();
const mockShell = Subject.create(frontendToShell, shellToFrontend);
const channels = mockShell;
const state$ = {
value: {
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels,
status: "not connected"
})
})
})
})
}),
app: {
notificationSystem: { addNotification: jest.fn() }
}
}
};
const action$ = ActionsObservable.of(
actions.sendExecuteRequest({
id: "id",
message: "test",
contentRef: "fakeContentRef"
})
);
const observable = createExecuteCellStream(
action$,
state$.value,
createMessage("execute_request"),
"id",
"fakeContentRef"
);
observable.pipe(toArray()).subscribe(
actions => {
const errors = actions.map(({ payload: { error } }) =>
error.toString()
);
expect(errors).toEqual(["Error: Kernel not connected!"]);
done();
},
err => done.fail(err)
);
});
示例4: filter
export function MakePostMessageSubject<T>(
thisWindow: Window,
destinationWindow: Window
): Subject<T> {
// Create an observe which will send the correct message given the Observable
// event. e.g. an error will trigger an error message to be posted.
const outboundMessages = {
next: (payload: T) =>
postMessage<T>(destinationWindow, {
id: POST_MESSAGE_IDENTIFIER,
type: PostMessageType.REGULAR_MESSAGE,
payload
}),
error: (error: any) =>
postMessage<T>(destinationWindow, {
id: POST_MESSAGE_IDENTIFIER,
type: PostMessageType.ERROR_MESSAGE,
error
}),
complete: () =>
postMessage<T>(destinationWindow, {
id: POST_MESSAGE_IDENTIFIER,
type: PostMessageType.COMPLETE_MESSAGE
})
};
// Extract the payload of inbound messages and handle obervable complete and
// error events.
const inboundPostMessages = fromEvent<Message<T>>(thisWindow, "message");
const closeMessages = inboundPostMessages.pipe(
filter(message => message.type === PostMessageType.COMPLETE_MESSAGE)
);
const inboundMessages = inboundPostMessages.pipe(
// Only accept widget post messages.
filter(message => message && message.id === POST_MESSAGE_IDENTIFIER),
// Throw an error locally if an error message is received.
tap(message => {
if (message.type === PostMessageType.ERROR_MESSAGE) {
throw new Error(message.error);
}
}),
// Complete when a completion message is received.
takeUntil(closeMessages.pipe(first())),
// Extract the payload of regular messages.
map(message => message.payload)
);
return Subject.create(outboundMessages, inboundMessages);
}
示例5: fromAddress
static fromAddress(address: string): Observable<MessageEvent> {
const ws = new WebSocket(address);
const observable = Observable.create((obs: Observer<any>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
});
const observer = Subscriber.create((data) => {
if (ws.readyState === WebSocket.OPEN) { ws.send(data); }
});
return Subject.create(observer, observable);
}
示例6: createWebsocket
public createWebsocket(url: string): Subject<MessageEvent> {
const socket = new WebSocket('wss://hohlbirne/backend.node.js');
const observable = Observable.create((observer_: Observer<MessageEvent>) => {
socket.onmessage = observer_.next.bind(observer_);
socket.onerror = observer_.error.bind(observer_);
socket.onclose = observer_.complete.bind(observer_);
return socket.close.bind(socket);
});
const observer = {
next: (data: Object) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(data));
}
console.log(socket.readyState, data);
}
};
return Subject.create(observer, observable);
}
示例7: it
it("handles code completion", done => {
const sent = new Subject();
const received = new Subject();
const mockSocket = Subject.create(sent, received);
const channels = mockSocket;
const cm = {
getCursor: () => ({ line: 2 }),
getValue: () => "\n\nimport thi",
indexFromPos: () => 12,
posFromIndex: x => ({ ch: x, line: 3 })
};
const message = createMessage("complete_request");
const observable = complete.codeCompleteObservable(channels, cm, message);
// Craft the response to their message
const response = createMessage("complete_reply");
response.content = {
matches: ["import this"],
cursor_start: 9,
cursor_end: 10
}; // Likely hokey values
response.parent_header = Object.assign({}, message.header);
// Listen on the Observable
observable.subscribe(
msg => {
expect(msg.from).toEqual({ line: 3, ch: 9 });
expect(msg.list[0].text).toEqual("import this");
expect(msg.to).toEqual({ ch: 10, line: 3 });
},
err => {
throw err;
},
done
);
received.next(response);
});
示例8: uuid
export const createMainChannelFromSockets = (
sockets: {
[name: string]: moduleJMP.Socket;
},
header: HeaderFiller = {
session: uuid(),
username: getUsername()
},
jmp = moduleJMP
): Channels => {
// The mega subject that encapsulates all the sockets as one multiplexed
// stream
const outgoingMessages = Subscriber.create<JupyterMessage>(
message => {
// There's always a chance that a bad message is sent, we'll ignore it
// instead of consuming it
if (!message || !message.channel) {
console.warn("message sent without a channel", message);
return;
}
const socket = sockets[message.channel];
if (!socket) {
// If, for some reason, a message is sent on a channel we don't have
// a socket for, warn about it but don't bomb the stream
console.warn("channel not understood for message", message);
return;
}
try {
const jMessage = new jmp.Message({
// Fold in the setup header to ease usage of messages on channels
header: { ...message.header, ...header },
parent_header: message.parent_header,
content: message.content,
metadata: message.metadata,
buffers: message.buffers
});
socket.send(jMessage);
} catch (err) {
console.error("Error sending message", err, message);
}
},
undefined, // not bothering with sending errors on
() =>
// When the subject is completed / disposed, close all the event
// listeners and shutdown the socket
Object.keys(sockets).forEach(name => {
const socket = sockets[name];
socket.removeAllListeners();
if (socket.close) socket.close();
})
);
// Messages from kernel on the sockets
const incomingMessages: Observable<JupyterMessage> = merge(
// Form an Observable with each socket
...Object.keys(sockets).map(name => {
const socket = sockets[name];
// fromEvent typings are broken. socket will work as an event target.
return fromEvent(
// Pending a refactor around jmp, this allows us to treat the socket
// as a normal event emitter
(socket as unknown) as FromEventTarget<JupyterMessage>,
"message"
).pipe(
map(
(body: JupyterMessage): JupyterMessage => {
// Route the message for the frontend by setting the channel
const msg = { ...body, channel: name };
// Conform to same message format as notebook websockets
// See https://github.com/n-riesco/jmp/issues/10
delete (msg as any).idents;
return msg;
}
),
publish(),
refCount()
);
})
).pipe(
publish(),
refCount()
);
const subject: Subject<JupyterMessage> = Subject.create(
outgoingMessages,
incomingMessages
);
return subject;
};
示例9: formWebSocketURL
export const connect = (
serverConfig: ServerConfig,
kernelID: string,
sessionID?: string
): Subject<any> => {
const wsSubject = webSocket<JupyterMessage>(
formWebSocketURL(serverConfig, kernelID, sessionID)
);
wsSubject.pipe(
retryWhen(error$ => {
// Keep track of how many times we've already re-tried
let counter = 0;
let maxRetries = 100;
return error$.pipe(
tap(e => {
counter++;
// This will only retry on error when it's a close event that is not
// from a .complete() of the websocket subject
if (counter > maxRetries || e instanceof Event === false) {
console.error(
`bubbling up Error on websocket after retrying ${counter} times out of ${maxRetries}`,
e
);
throw e;
} else {
// We'll retry at this point
console.log(`attempting to retry kernel connection after error`, e);
}
}),
delay(1000)
);
}),
// The websocket subject is multicast and we need the retryWhen logic to retain that property
share()
);
// Create a subject that does some of the handling inline for the session
// and ensuring it's serialized
return Subject.create(
Subscriber.create(
(message?: JupyterMessage) => {
if (typeof message === "object") {
const sessionizedMessage = {
...message,
header: {
session: sessionID,
...message.header
}
};
wsSubject.next(sessionizedMessage);
} else {
console.error("Message must be an object, the app sent", message);
}
},
(e: Error) => wsSubject.error(e),
() => wsSubject.complete()
), // Subscriber
// Subject.create takes a subscriber and an observable. We're only
// overriding the subscriber here so we pass the subject on as an
// observable as the second argument to Subject.create (since it's
// _also_ an observable)
wsSubject
);
};