Skip to content

Instantly share code, notes, and snippets.

@stefanotroia
Created November 26, 2019 06:58
Show Gist options
  • Save stefanotroia/a8c36289694012bbb491ec23f14184fb to your computer and use it in GitHub Desktop.
Save stefanotroia/a8c36289694012bbb491ec23f14184fb to your computer and use it in GitHub Desktop.
Firebase Notification Service
@Service
@Slf4j
public class NotificationService {
@Autowired
private Config config;
private EmitterProcessor<Notification> emitterSource = EmitterProcessor.create();
private Flux<Notification> fluxNotification = emitterSource.publish().autoConnect();
@PostConstruct
private void init() {
try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(new ByteArrayInputStream(config.getFirebasePrivateKey().getBytes(StandardCharsets.UTF_8))))
.build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
log.error("Error initializating Firebase SDK");
}
//SIMPLE FLUX NOTIFICATION DISPATCHER
fluxNotification.parallel()
.doOnNext(this::sendNotification)
.subscribe();
}
//METHOD CALLED BY NOTIFICATON PRODUCER
public Mono<Void> addNotification(NotifcationTransit notify) {
emitterSource.onNext(notify);
return Mono.empty();
}
private void sendNotification(NotifcationTransit transit) {
try {
FirebaseMessaging.getInstance().send(Message.builder()
.setToken(transit.getToken())
.setNotification(Notification.builder()
.setTitle(NOTIFY_TITLE)
.setBody(NOTIFY_BODY)
.build())
.build());
} catch (FirebaseMessagingException e) {
log.error("[{}] {}",e.getErrorCode(),e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment