-
-
Save alekpopovic/6ff8b7db229425b1506f8d94c6948eee to your computer and use it in GitHub Desktop.
Using ActionCable in Expo/React Native
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # config/routes.rb | |
| Rails.application.routes.draw do | |
| mount ActionCable.server, at: '/cable' | |
| end | |
| # app/channels/chat_channel.rb | |
| class ChatChannel < ApplicationCable::Channel | |
| def subscribed | |
| stream_from "chat_channel" | |
| end | |
| def unsubscribed | |
| end | |
| def speak(data) | |
| ActionCable.server.broadcast("chat_channel", message: "#{data["message"]}") | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Goes inside componentDidMount() in any screen | |
| this.ws = new WebSocket('ws://0.0.0.0:3000/cable'); | |
| this.channel_name = 'ChatChannel'; | |
| this._handleMessage = (data) => { | |
| this.setState({ | |
| messages: this.state.messages.concat([data.message.message]) | |
| }) | |
| } | |
| this.ws.onopen = () => { | |
| const msg = { | |
| command: 'subscribe', | |
| identifier: JSON.stringify({ | |
| channel: this.channel_name, | |
| }), | |
| }; | |
| this.ws.send(JSON.stringify(msg)); | |
| }; | |
| this.ws.onmessage = e => { | |
| var data = JSON.parse(e.data); | |
| if (data.identifier != undefined) { | |
| data.identifier = JSON.parse(data.identifier) | |
| } | |
| if (data.type == "welcome" || data.type == "ping" || data.type == "confirm_subscription") { | |
| return; | |
| } | |
| if (data.identifier.channel == this.channel_name) { | |
| this._handleMessage(data) | |
| return; | |
| } | |
| }; | |
| this.ws.onerror = e => { | |
| console.log("ERROR: " + e.message); | |
| }; | |
| this.ws.onclose = e => { | |
| console.log("CONNECTION CLOSED: " + e.code + " " + e.reason); | |
| }; | |
| this.ws.sendmessage = data => { | |
| const msg = { | |
| command: 'message', | |
| identifier: JSON.stringify({ | |
| channel: 'ChatChannel', | |
| }), | |
| data: JSON.stringify(data) | |
| }; | |
| this.ws.send(JSON.stringify(msg)); | |
| } | |
| # Somewhere in the code | |
| _sendMessage = (message) => { | |
| this.ws.sendmessage({ | |
| action: 'speak', | |
| message: message, | |
| }); | |
| } | |
| <TouchableOpacity onPress={() => this._sendMessage("Hello world!)}> | |
| <Text> | |
| Send message | |
| </Text> | |
| </TouchableOpacity> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment