Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple Demo #140

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions _Simple_Demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Simple_Scarlet_WebSocket
Guide on how to set up an app using Scarlet. \
It's much easier to read than the demo app. It could be a good starting point for understanding the library.
## Requirements
To follow this guide you need to know:
- The basics of ViewModel (check out my guide: https://github.com/lolloz98/Android_ViewModel)
- The basics of databinding (https://developer.android.com/topic/libraries/data-binding)
- (Very basics of the navigation component)
- install nodejs on your computer https://nodejs.org/it/download/
- Create a ngrok account and install the program on your computer (https://dashboard.ngrok.com/signup)
## Description
This is a really simple app: we create a connection with our own server and we send and receive messages after having established a connection.
![](/_Simple_Demo/img/Global_understanding.PNG)
## Setup server
In \_Simple\_Demo folder you find simple_server. \
Using nodejs you can launch the script server.js:
```node server.js``` \
Remember to install the dependecies:
```npm install ws``` \
If you open a command window you can use:
```
ngrok http 8080
```
Now you have access to your computer from the web. You will use the http address given but, you will have to switch protocol (you just need to change http:// with wss://). \
Your server is good to go :)
## Setup Android app
Before starting our app remember to change the BASE_URL (with: wss://your_ngrok_http.ngrok.io) in network.MyWebSocketAPI file. \
If you don't do that, the app won't be able to connect to the server.
## Important notes
Bonus: I use Timber to log messages. https://github.com/JakeWharton/timber
## References
https://github.com/Tinder/Scarlet
14 changes: 14 additions & 0 deletions _Simple_Demo/Simple_Scarlet_WebSocket_kotlin/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
63 changes: 63 additions & 0 deletions _Simple_Demo/Simple_Scarlet_WebSocket_kotlin/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
compileSdkVersion 29

dataBinding {
enabled = true
}

defaultConfig {
applicationId "com.carpa.simple_scarlet_websocket_kotlin"
minSdkVersion 24
targetSdkVersion 29
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

//Navigation component
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'

//Scarlet library
implementation 'com.tinder.scarlet:scarlet:0.1.10'

//Scarlet helpers
implementation 'com.tinder.scarlet:message-adapter-moshi:0.1.10'
implementation 'com.tinder.scarlet:stream-adapter-rxjava2:0.1.10'
implementation 'com.tinder.scarlet:message-adapter-protobuf:0.1.10'
implementation 'com.tinder.scarlet:lifecycle-android:0.1.10'
implementation "com.tinder.scarlet:websocket-okhttp:0.1.10"

//For logging
implementation 'com.jakewharton.timber:timber:4.7.1'

//For LiveDataReactiveStreams
implementation 'androidx.lifecycle:lifecycle-reactivestreams:2.2.0'

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.carpa.simple_scarlet_websocket_kotlin

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.carpa.simple_websocket_kotlin", appContext.packageName)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.carpa.simple_scarlet_websocket_kotlin">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:name="com.carpa.simple_scarlet_websocket_kotlin.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.carpa.simple_scarlet_websocket_kotlin.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.carpa.simple_scarlet_websocket_kotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.carpa.simple_scarlet_websocket_kotlin

import android.app.Application
import timber.log.Timber

class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
//useful for setting up Timber for logging information.
//Remember to add the dependency in the manifest :)
Timber.plant(Timber.DebugTree())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.carpa.simple_scarlet_websocket_kotlin.lifecycle

import android.content.res.Configuration
import com.tinder.scarlet.Lifecycle
import com.tinder.scarlet.lifecycle.LifecycleRegistry
import io.reactivex.Flowable
import io.reactivex.processors.BehaviorProcessor
import timber.log.Timber

/**
* Mock-up lifecycle just to see how it should be created.
* If we add .combineWith(CustomLifecycle...) in scarlet declaration (in MyWebSocketAPI) in lifecycle,
* this will stop the WebSocket whenever we are not in portrait mode :)
* NOT Implemented: if you want, try it (follow instruction below)
* - Add .combineWith(CustomLifecycle...) in scarlet declaration (in MyWebSocketAPI) in lifecycle
* - override onConfigurationChanged in MyApplication and from there call
* PortraitModeObserver.updateConfig(newConfig.orientation)
* BEWARE: I am not sure if this is the best way to do it, it is just a silly example. :)
* For more info check the loggedInLifecycle at:
* https://github.com/Tinder/Scarlet/blob/master/demo/src/main/java/com/tinder/app/echo/domain/LoggedInLifecycle.kt
*/
class CustomLifecycle(portraitModeObserver: PortraitModeObserver,
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry()
) : Lifecycle by lifecycleRegistry {
init{
portraitModeObserver.observeMode().map{
when(it){
Configuration.ORIENTATION_PORTRAIT -> {
Lifecycle.State.Started
}
else -> {
Timber.d("Configuration changed: stopping connection")
Lifecycle.State.Stopped.WithReason()
}
}
}.subscribe(lifecycleRegistry)
}
}

object PortraitModeObserver{
private val portraitModeBehavProc = BehaviorProcessor.createDefault(Configuration.ORIENTATION_PORTRAIT)

fun observeMode() : Flowable<Int> = portraitModeBehavProc

fun updateConfig(newConf: Int) {
portraitModeBehavProc.onNext(newConf)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.carpa.simple_scarlet_websocket_kotlin.main

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.carpa.simple_scarlet_websocket_kotlin.R
import com.carpa.simple_scarlet_websocket_kotlin.databinding.FragmentMainBinding
import com.carpa.simple_scarlet_websocket_kotlin.network.MyWebSocketAPI

class MainFragment : Fragment() {

/**
* We create the viewModel only once.
*/
private val viewModel by lazy {
ViewModelProvider(
this,
MainViewModelFactory(MyWebSocketAPI.getInstance(requireActivity().application).socketService)
).get(MainViewModel::class.java)
}

@SuppressLint("CheckResult")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment using data binding
val binding = DataBindingUtil.inflate<FragmentMainBinding>(
inflater,
R.layout.fragment_main,
container,
false
)

binding.viewModel = viewModel

binding.lifecycleOwner = this

return binding.root
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.carpa.simple_scarlet_websocket_kotlin.main

import android.annotation.SuppressLint
import android.widget.EditText
import androidx.lifecycle.*
import com.carpa.simple_scarlet_websocket_kotlin.network.Msg
import com.carpa.simple_scarlet_websocket_kotlin.network.SocketService
import com.tinder.scarlet.WebSocket
import timber.log.Timber

class MainViewModel(private val socketService: SocketService) : ViewModel() {
// We use data binding to connect LiveData/onClick methods to views (look at layout files)
fun onSendMsg(text: EditText){
socketService.sendText(
Msg(
text.text.toString()
)
)
}

val msgRec: LiveData<Msg> =
LiveDataReactiveStreams.fromPublisher<Msg> (
socketService.observeText()
)

val isConnected: LiveData<Boolean> =
LiveDataReactiveStreams.fromPublisher (
socketService.observeWebSocketEvent().map{
when(it){
is WebSocket.Event.OnConnectionOpened<*> -> Timber.d("Connection opened")
is WebSocket.Event.OnMessageReceived -> Timber.d("Message received")
is WebSocket.Event.OnConnectionClosing -> Timber.d("Connection closing")
is WebSocket.Event.OnConnectionClosed -> Timber.d("Connection closed")
is WebSocket.Event.OnConnectionFailed -> Timber.d("Connection failed")
}
(it is WebSocket.Event.OnConnectionOpened<*> || it is WebSocket.Event.OnMessageReceived)
}
)

/**
* Example: another way (we already have [isConnected]) to see the status of the connection :)
*/
@SuppressLint("CheckResult")
fun observeWebSocketEvent(){
socketService.observeWebSocketEvent()
.subscribe {
when(it){
is WebSocket.Event.OnConnectionOpened<*> -> Timber.d("Connection opened")
is WebSocket.Event.OnMessageReceived -> Timber.d("Message received")
is WebSocket.Event.OnConnectionClosing -> Timber.d("Connection closing")
is WebSocket.Event.OnConnectionClosed -> Timber.d("Connection closed")
is WebSocket.Event.OnConnectionFailed -> Timber.d("Connection failed")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.carpa.simple_scarlet_websocket_kotlin.main

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.carpa.simple_scarlet_websocket_kotlin.network.SocketService

class MainViewModelFactory(private val socketService: SocketService
) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
return MainViewModel(socketService) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
Loading