私の理解によれば、Observable.createと通常のjavascript関数はどちらも私に似ています。では、両者の実際の違いは何ですか?
これらは両方とも単なる機能です。 Observablesは暗い魔法のように見えるかもしれませんが、Javascriptのオブジェクトや機能には影響します。
基本的には、最初にが必要です。今、だから我々はそれの関数への参照渡し、観察可能なを作成するために
Observable.create(
function(observer)
) : Observable {}
Observable.create
の署名を検討
{
//a function to be executed when we want the Observable to emit. Takes 1 arg
next: (val) : void
//a func to be executed when an uncaught exception occurs. Takes 1 arg
error: (err) : void
//a func to be executed when we want the Observable to stop. Takes no arg
complete:() : void
}
:これは3つのプロパティを持つだけのオブジェクトです。この関数はすぐには実行されませんが、Observableの.subscribe()
を呼び出してcreate()
が返されたときに実行されます。
意味を分かりやすくするために、変更するたびにテキスト入力の新しい値を放出するオブザーバブルを作成するとします。
let obs = Observable.create(observer=>{
let input = document.querySelector('#myInput');
input.onchange = (event) => {
let newVal = event.target.value;
if(newVal == 'stop') observer.complete();
else observer.next(event.target.value);
}
});
私たちは、この時点で持っているすべては、私たちがサブスクライブを呼び出すときに実行される関数を記憶しているオブジェクトobs
です。このファンクションはインタフェースを考慮したパラメータを必要とするため、subscribe
は3つのパラメータを取ることが理にかなっています。我々は値の変更をリスニングを開始する準備ができたら:
obs.subscribe(
// this is the function that will be called from within the Observable
// when the value changes. Behind the scenes this function is just
// assigned to observer.next
newVal => {console.log(newVal)},
error => {}, // assigned to observer.error
() => {} // assigned to observer.complete. Executed if new val is 'stop'
)
を今、あなたはonchange
イベントが入力で発生するたびに、observer.next(newVal)
は.subscribe()
の第一引数の別名である、と呼ばれているか、見!
私の意見では、Observableを素晴らしいものにするのは、どうやって連鎖したり構成したりできるかということです。たぶん、私はすべての価値の変化について学ぶことに興味がありませんが、長さが3以上のものだけに興味があります。何を渡されたが関数であることを
obs.filter(newVal => newVal.length > 3).subscribe('...')
は予告:代わりに元obs
に加入するのは、私は.filter()
演算子を適用します。最終結果は、フィルタを通過する出力のみが.subscribe()
に達することになります。それはどうですか?このようなもの:
class Observable {
filter: (filterFunc) {
// create a new observable. This is now what your code will subscribe to.
// the original observable is now upstream, and accessed below
return Observable.create(observer => {
// subscribe to the original observable so we can see input value changes
this.subscribe(
// pass on the value only if it makes it through the filter
newVal => {if(filterFunc(newVal)) observer.next(newVal)},
// errors flow downstream
error => observer.error(error),
// Stop immediately if the upstream observable completes
complete => observer.complete()
);
})
}
}
もう一度、魔法はありません。 .filter()
演算子は、元の観測値にサブスクライブした新しい観測値を作成しました。オリジナルが放出されると、newはその値を受け取り、その結果をオブザーバに渡す前にその値を操作します。したがって、obs.filter(filterFunc).subscribe()
を実行すると、2番目のオブザーバの出力が表示されます。 Observablesを非常に強力にする数字とflexibility of these operatorsとと通知したときのデザインパラダイム。
RxJS 5のアーキテクトがthis videoをお勧めします。同じアーキテクトでわずか数分の場合は、look at this postです。
Observableが重要な理由についてのヒントは次のとおりです。非同期関数からどのように値を返すのですか?別のコードが関数を呼び出すときに通知を受けたい場合はどうすればよいですか? 'setInterval'で呼び出された関数を持っていて、その結果を別の間隔で実行される別の関数とどういう組み合わせにしたいのでしょうか?それは人為的に聞こえるかもしれませんが、そのようなことはいつもgamedevで起こります。 –