私はiPhoneアプリを持っています。ここでは、現在アイテムを表示している人の数を表示したいと思います。
私は、ユーザーがビューに入るときにこのトランザクションを実行することでそれを行っています(以下のRubymotionコードですが、Firebase iOS SDKとまったく同じように機能します)。
listing_reference[:listings][self.id][:viewing_amount].transaction do |data|
data.value = data.value.to_i + 1
FTransactionResult.successWithValue(data)
end
そして、彼らがビューを出るとき:
listing_reference[:listings][self.id][:viewing_amount].transaction do |data|
data.value = data.value.to_i + -
FTransactionResult.successWithValue(data)
end
ほとんどの場合は正常に機能しますが、問題が発生することもあります。アプリがクラッシュしたり、接続が失われたりします。
I've been looking at "onDisconnect" to solve this - https://firebase.google.com/docs/reference/ios/firebasedatabase/interface_f_i_r_database_reference#method-detail - but from what I can see, there's no "inDisconnectRunTransaction".
How can I make sure that the viewing amount on the listing gets decremented no matter what?
A Firebase Database transaction runs as a compare-and-set operation: given the current value of a node, your code specifies the new value. This requires at least one round-trip between the client and server, which means that it is inherently unsuitable for onDisconnect()
operations.
onDisconnect()
ハンドラではなく、単純ですset()
操作:あなたはハンドラをアタッチするとき、あなたは、クライアントが(どちらかきれいか、思わず自分の問題の場合のように)切断されたことをするとき、サーバの検出が起こるしたいのか、書き込み操作、指定します。
解決策は(NoSQLデータベースでよくあることですが)状況を適切に処理するデータモデルを使用することです。あなたの場合、視聴者の数ではなく、uid
各視聴者の数を保存するのが最も自然なようです。
itemViewers
$itemId
uid_1: true
uid_2: true
uid_3: true
これで、単純なvalue
リスナーで視聴者の数を取得できます。
ref.child('itemViewers').child(itemId).on('value', function(snapshot) {
console.log(snapshot.numChildren());
});
そして、以下onDisconnect()
を使用してクリーンアップします。
ref.child('itemViewers').child(itemId).child(authData.uid).remove();
どちらのコードスニペットもJavaScript構文になっています。これは、入力した後にSwiftを使用していることに気付いたためです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加