• This repository has been archived on 09/Aug/2020
  • Stars
    star
    115
  • Rank 305,916 (Top 7 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

RxJava extension for Android Firebase Cloud Messaging (aka fcm).

⚠️ Deprecated: this library is no longer mantained. ⚠️

Android Arsenal

RxFcm

RxJava extension for Firebase Cloud Messaging which acts as an architectural approach to easily satisfy the requirements of an android app when dealing with push notifications.

Features:

  • Remove android boilerplate code (not need for Manifest or Service(s) configuration).
  • Decouple presentation responsibilities from data responsibilities when receiving notifications.
  • Deploy a targeting strategy to aim for the desired Activity/Fragment when receiving notifications.

Setup

Add RxFcm dependency and Google Services plugin to project level build.gradle.

apply plugin: 'com.google.gms.google-services'

dependencies {
    compile 'com.github.VictorAlbertos:RxFcm:0.1.5-2.x'
    compile 'com.google.firebase:firebase-messaging:17.0.0'
}

Add Google Services to classpath and jitpack repository to root level build.gradle.

dependencies {
    classpath 'com.google.gms:google-services:3.1.1'
}

allprojects {
    repositories {
        //..
        maven { url "https://jitpack.io" }
    }
}

There is, thought, one step behind which RxFcm can't do for you. You have to go to firebase consolse, create a google-services.json configuration file and place it in your Android application module. (This is a simple tutorial about how to do it)

Usage

FcmReceiverData

FcmReceiverData implementation should be responsible for updating the data models. The onNotification method requires to return an instance of the observable supplied as argument, after applying doOnNext operator to perform the update action:

public class AppFcmReceiverData implements FcmReceiverData {

  
 
 	@Override public Observable<Message> onNotification(Observable<Message> oMessage) {
        
 		return oMessage.doOnNext(message -> {});
    
 	}

 	
 }

The observable type is an instance of Message, which holds a reference to the android Application instance, the Bundle notification and a method called target(), which returns the key associated with this notification.

public class AppFcmReceiverData implements FcmReceiverData {

    @Override public Observable<Message> onNotification(Observable<Message> oMessage) {
        return oMessage.doOnNext(message -> {
            Bundle payload = message.payload();

            String title = payload.getString("title");
            String body = payload.getString("body");

            if (message.target().equals("issues")) SimpleCache.addIssue(new Notification(title, body));
            else if (message.target().equals("supplies")) SimpleCache.addSupply(new Notification(title, body));
        });
    }
    
} 

To RxFcm be able to return a not null string value when calling target() method, you need to add the key rx_fcm_key_target to the payload of the push notification:

{ 
  "data": {
    "title":"A title 4",
    "body":"A body 4",
    "rx_fcm_key_target":"supplies"
  },
  "to":"token_device"
  }
}

If rx_fcm_key_target is not added to the json payload, you will get a null value when calling the target() method. So, you can ignore this, but you would be missing the benefits of the targeting strategy.

Alternatively, if you don't have access to the server code, you can supply a custom key when you register the RxFcm classses.

FcmReceiverUIBackground and FcmReceiverUIForeground

Both of them will be called only after FcmReceiverData observable has reached onCompleted() state. This way it’s safe to assume that any operation related to updating the data model has been successfully achieved, and now it’s time to reflect these updates in the presentation layer.

FcmReceiverUIBackground

FcmReceiverUIBackground implementation will be called when a notification is received and the application is in the background. Probably the implementation class will be responsable for building and showing system notifications.

public class AppFcmReceiverUIBackground implements FcmReceiverUIBackground {

 
   
	@Override public void onNotification(Observable<Message> oMessage) {
        
		oMessage.subscribe(message -> buildAndShowNotification(message));
    
	}
	
}

FcmReceiverUIForeground

FcmReceiverUIForeground implementation will be called when a notification is received and the application is in the foreground. The implementation class must be an Activity or an android.support.v4.app.Fragment. FcmReceiverUIForeground exposes a method called matchesTarget(), which receives an string (the value of the rx_fcm_key_target node payload notification) and forces to the implementation class to return a boolean.

If the current Activity or visible Fragment matchesTarget() method returns true, onTargetNotification() method will be called, otherwise onMismatchTargetNotification() method will be called.

public abstract class BaseFragment extends android.support.v4.app.Fragment implements FcmReceiverUIForeground {

    
	
    @Override public void onMismatchTargetNotification(Observable<Message> oMessage) {
        oMessage.subscribe(message -> {
            showAlert(message);
        });
    }  
	 

}
public class FragmentIssues extends BaseFragment {

    
	
    @Override public void onTargetNotification(Observable<Message> oMessage) {
        oMessage.subscribe(message -> {
            notificationAdapter.notifyDataSetChanged();
        });
    }   
	 
    @Override public boolean matchesTarget(String key) {
        return "issues".equals(key);
    }
	 

}
public class FragmentSupplies extends android.support.v4.app.Fragment implements FcmReceiverUIForeground {

    
	
    @Override public void onTargetNotification(Observable<Message> oMessage) {
        oMessage.subscribe(message -> {
            notificationAdapter.notifyDataSetChanged();
        });
    }     
	 

	@Override public boolean matchesTarget(String key) {
        return "supplies".equals(key);
    }
}

Limitation:: Your fragments need to extend from android.support.v4.app.Fragment instead of android.app.Fragment, otherwise they won't be notified.

RefreshTokenReceiver

FcmRefreshTokenReceiver implementation will be called when the token has been updated. As the documentation points out, the token device may need to be refreshed for some particular reason.

public class RefreshTokenReceiver implements FcmRefreshTokenReceiver {
    
    @Override public void onTokenReceive(Observable<TokenUpdate> oTokenUpdate) {
        oTokenUpdate.subscribe(tokenUpdate -> {}, error -> {});
    }
    
}

Retrieving current token

If at some point you need to retrieve the fcm token device -e.g for updating the value on your server, you could do it easily calling RxFcm.Notifications.currentToken:

    RxFcm.Notifications.currentToken().subscribe(token -> {}, error -> {});

Register RxFcm classes

Once you have implemented FcmReceiverData and FcmReceiverUIBackground interfaces is time to register them in your Android Application class calling RxFcm.Notifications.init. Plus, register RefreshTokenReceiver implementation too at this point.

public class RxSampleApp extends Application {

    @Override public void onCreate() {
        super.onCreate();

        RxFcm.Notifications.init(this, new AppFcmReceiverData(), new AppFcmReceiverUIBackground()); 
        
        //If you need to supply a custom key for the json payload use this overloaded version.
        RxFcm.Notifications.init(this, new AppFcmReceiverData(), new AppFcmReceiverUIBackground(), "rx_fcm_custom_key");  
                
        RxFcm.Notifications.onRefreshToken(new RefreshTokenReceiver());
    }

}

Mocking support.

To mock a call to RxFcm with a bundle which will be process as a real Fcm notification use:

    RxFcmMock.Notifications.newNotification(bundle); 

To mock a call to RxFcm requesting it to update the token device:

    RxFcmMock.Notifications.updateToken(); 

Examples

There is a complete example of RxFcm in the app module. Plus, it has an integration test managed by Espresso test kit which shows several uses cases.

Testing notification

You can easily send http post request to Firebase Cloud Messaging server using Postman or Advanced Rest Client.

Author

Víctor Albertos

Another author's libraries:

  • Mockery: Android and Java library for mocking and testing networking layers with built-in support for Retrofit.
  • RxCache: Reactive caching library for Android and Java.
  • RxActivityResult: A reactive-tiny-badass-vindictive library to break with the OnActivityResult implementation as it breaks the observables chain.
  • RxSocialConnect: OAuth RxJava extension for Android.

More Repositories

1

RxCache

Reactive caching library for Android and Java
Java
2,375
star
2

BreadcrumbsView

A customizable Android view for paginated forms
Java
684
star
3

RxActivityResult

A reactive-tiny-badass-vindictive library to break with the OnActivityResult implementation as it breaks the observable chain.
Java
595
star
4

RxSocialConnect-Android

OAuth RxJava extension for Android.
Java
257
star
5

SwipeCoordinator

A coordinator layout for Android views to animate and typify touch events as swipe gestures
Java
253
star
6

ReactiveCache

A reactive cache for Android and Java which honors the reactive chain.
Java
242
star
7

Mockery

Android and Java library for mocking and testing networking layers with built-in support for Retrofit.
Java
145
star
8

RxCacheSamples

How to use RxCache for both Android and Java projects
Java
116
star
9

RxPermissionsResult

Ask for permissions without breaking the observable chain.
Java
109
star
10

DeviceAnimationTestRule

A JUnit rule to disable and enable device animations
Kotlin
106
star
11

RxGcm

[DEPRECATED] RxJava extension for Android Google Cloud Messaging (aka gcm).
Java
95
star
12

Jolyglot

Agnostic Json abstraction to perform data binding operations for Android and Java.
Java
70
star
13

RestAPIParseAuthCleanAndroid

An android implementation of an authentication system based on the Parse Api using the design patters suggested by Robert C. Martin (aka Uncle Bob) on his “clean architecture”.
Java
45
star
14

KDirtyAndroid

A dirty approach for truly client Android applications using Kotlin
Kotlin
17
star
15

DirtyAndroid

A dirty approach for truly client Android applications
Java
15
star
16

RxLifecycleInterop

[DEPRECATED] Workaround for using RxLifecycle with RxJava2
Java
10
star
17

Pacman

The classic video game Pacman for iOS and Android made with Unity 2d
C#
9
star
18

ml_technical_analysis

A machine learning approach integrating technical analysis to forecast stock prices
Python
8
star
19

EventBus-Samples

A simple demonstration about how to use EventBus with Activities, Fragments and Services on Android.
Java
7
star
20

android-kotlin-adoption

Kotlin adoption on the Android open source community
Python
6
star
21

Near-friends

App to know where your contacts are at every time
Java
3
star
22

bs-blockchain-hackathon-team4

BS Blockchain Hackathon Team 4 Repo
JavaScript
2
star
23

github-pr-latency-ml

A failed attempt (so far) to predict Github Pull Request latency.
Python
1
star
24

kotlin-apuntes

Kotlin
1
star