之前做的兩個項目都涉及到即時通訊功能,近期幫朋友開發小程序時也有這個需求,因為沒有后端,所以決定使用雲開發來實現通訊功能。
即時通訊的關鍵點在於即時,在之前的開發中我們可以通過websocket長連接來實現,雲開發又怎樣來完成這項功能呢?
通過查閱小程序官方文檔,我們發現collection.watch()方法可以實現數據監聽,官方說明為:
監聽集合中符合查詢條件的數據的更新事件。使用 watch 時,支持 where, orderBy, limit,不支持 field。
這樣一來我們邊可以通過wach方法監聽指定聊天室的數據更新(將A B用戶的聊天關系記錄為一條聊天室數據,通過id進行唯一標識)
具體代碼如下:
1 // 監聽數據變化 2 let _db = db.collection('msgList') 3 _db 4 .where({id: this.data.id}) 5 .watch({ 6 // 成功回調 7 onChange: function(snapshot) { 8 let reviceMsg = snapshot.docChanges[0] 9 if(reviceMsg.dataType == 'add'){ 10 console.log(reviceMsg.doc) 11 let talkData = that.data.talkData 12 talkData.push(reviceMsg.doc) 13 that.setData({ 14 talkData: talkData 15 }) 16 } 17 }, 18 // 失敗回調 19 onError: function(err) { 20 console.error('the watch closed because of error', err) 21 } 22 })
