[英]Unsubscribing from an observable when another observable is unsubscribed
[英]Retrieve values from one observable when an event happens in another observable
假設我有兩個流。
每次值更改時,我都會在值流中獲取該值。
每次按下按鈕時,都會在按鈕流中收到一個事件。
當我在buttonPresses流中獲得一個事件時,我想做些什么,並在值流中使用最新的值。 例如,進行API調用。
但是,我不希望每次值更改時都會發生任何事情。
我認為這是一個“可觀察的思維”問題。 這是我正在努力的實際代碼。
/**
* Provides a stream of POSTCODE_LOOKUP action events
* @type {Object}
*/
export let PostcodeLookupActionsStream = Actions.stream
.filter( action => action.key === KEYS.POSTCODE_LOOKUP );
/**
* Provides a stream of values from a post code input field.
* @type {Object}
*/
export let PostCodeValueStream = Actions.stream
.filter( action => action.key === KEYS.POSTCODE_CHANGE )
.map( action => action.payload.postcode )
.shareReplay(1);
// Combine the two streams....?
export let PostCodeLookupStream = Rx.Observable
.merge(PostCodeValueStream, PostcodeLookupActionsStream)
.map( (value, action) => value);
/**
* Provides a stream of address retrieved from a postcode lookup
* @type {Array}
*/
export let AddressStream = PostCodeLookupStream
.flatMapLatest( postcode => MyAPI.postcodeLookup( postcode ) )
.flatMap( response => response.json() )
.shareReplay(1);
答案是使用withLatestFrom
。 我不知道為什么要花這么長時間在文檔中找到它,但是確實做到了。
/**
* Provides a stream of POSTCODE_LOOKUP events
* e.g: A stream of postcodes.
* @type {Object} a mouse event
*/
export let PostcodeLookupIntentsStream = Actions.stream
.filter( action => action.key === KEYS.POSTCODE_LOOKUP );
/**
* Provides a stream of values from a post code input field
* @type {String}
*/
export let PostCodeValueStream = Actions.stream
.filter( action => action.key === KEYS.POSTCODE_CHANGE )
.map( action => action.payload.postcode )
.shareReplay(1);
/**
* Combines `PostcodeLookupIntentsStream` and `PostCodeValueStream` to
* produce a stream of postcode values. New postcode values are emitted
* every time an event is emitted from the
* `PostcodeLookupIntentsStream`
*/
export let PostCodeLookupValueStream = PostcodeLookupIntentsStream
.withLatestFrom( PostCodeValueStream, (action, value) => value );
/**
* Provides a stream of address retrieved from a postcode lookup
* @type {Array}
*/
export let AddressStream = PostCodeLookupStream
.flatMapLatest( postcode => return MyAPI.postcodeLookup( postcode ) )
.flatMap( response => response.json() )
.shareReplay(1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.