Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava and random sporadic events on Android

I want to use RxJava like I would used Guava's EventBus or Otto, but I don't see how I can get it to function that way.

This is the scenario: let's say I want to have a button in my Android app and every time a button is pressed I want RxJava to emit an event via my Observable. It seems to me that I have to have the service reregister after it gets an event and that the activity would need to create a new observable as well.

Like if I say

Observable.from(x)

seems to me I would need to that for every event, but that creates a new observable that would need to be registered to again. Surely I am missing something.

like image 593
arinte Avatar asked Oct 09 '13 08:10

arinte


People also ask

What is the advantage of RxJava in Android?

RxJava provides a standard workflow that is used to manage all data and events across the application like Create an Observable> Give the Observable some data to emit> Create an Observer> Subscribe the Observer to the Observable. RxJava is becoming more and more popular particularly for Android developers.

How does RxJava work on Android?

RxJava is a JVM library that uses observable sequences to perform asynchronous and event-based programming. Its primary building blocks are triple O's, which stand for Operator, Observer, and Observables. And we use them to complete asynchronous tasks in our project. It greatly simplifies multithreading in our project.


1 Answers

You may want to do something like this (from rx.subjects.PublishSubject):

PublishSubject<Object> subject = PublishSubject.create();
// observer1 will receive all onNext and onCompleted events
subject.subscribe(observer1);
subject.onNext("one");
subject.onNext("two");
// observer2 will only receive "three" and onCompleted
subject.subscribe(observer2);
subject.onNext("three");
subject.onCompleted();

If you could inject the Subject interface into the Service and the PublishSubject into the Activity (or vice versa depending on what your doing) you can have a good separation of concerns.

like image 92
Bobby Hargett Avatar answered Sep 21 '22 11:09

Bobby Hargett