Using Observable in Android

observable android kotlin
rxjava observable
rxjava observable example
android observable vs livedata
livedata (android)
observablearraylist android
android reactive programming
learn rxjava android

I want to implement a Navigation View with many fragments that depend totally on a value defined in the MainActivity. I know that variables in MainActivity can be accessed using method defined in MainActivity from other Fragments to get the value, but the catch here is that the value of the variable in MainActivity may change (which runs on an AsyncThread). Now, I either change the code such that my Fragments update their value based on some event in the fragment itself or use SharedPreference. But I don't want to use SharedPreferences, neither have to check for change in the value unnecessarily many times.

I know in RxJS, we use Observable that runs Asynchronously and works in a fashion similar to a conveyor belt. A bit of googling through the official docs : Observable confirmed my suspicion of something similar being available in Android, but couldn't find any proper Tutorial or explanation on how to implement it. So, am looking for a simple code snippet that might give clarity to how Observable works in Android and if it is Async and if its based similar to RxJS implementation of it. (No, I don't want RxJS implementation)

Test Case:

MainActivity : int a, b (need observable for both variables)
Frag1 : int a1 , b1, a1changed(),b1changed()
Frag2 : int a2 , b2, a2Changed(), b2changed()

MainActivity contains integers whose value when changed should reflect in corresponding integers across the Fragments and calls separate function for each Fragment on the change being noticed.

Here is a simple example with an Activity and a single Fragment but it will be the same with other fragments.

First you need to create a class standing for the value you want to observe, in your case it's a simple int so create a class containing this int and that extends Observable (it implements Serializable to simplify exchange between activity and fragment):

...
import java.util.Observable;

public class ObservableInteger extends Observable implements Serializable {

    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
        this.setChanged();
        this.notifyObservers(value);
    }
}

Then use this observable int in an activity (activity layout contains a Button and a FrameLayout used to display a Fragment):

public class MainActivity extends Activity {

    private ObservableInteger a;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create observable int
        a = new ObservableInteger();
        // Set a default value to it
        a.setValue(0);

        // Create frag1
        Frag1 frag1 = new Frag1();
        Bundle args = new Bundle();
        // Put observable int (That why ObservableInteger implements Serializable)
        args.putSerializable(Frag1.PARAM, a);
        frag1.setArguments(args);

        // Add frag1 on screen
        getFragmentManager().beginTransaction().add(R.id.container, frag1).commit();

        // Add a button to change value of a dynamically
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set a new value in a
                a.setValue(a.getValue() + 1);
            }
        });
    }
}

Finally, create a Fragment that listen a value change:

...
import java.util.Observer;

public class Frag1 extends Fragment {
    public static final String PARAM = "param";

    private ObservableInteger a1;
    private Observer a1Changed = new Observer() {
        @Override
        public void update(Observable o, Object newValue) {
            // a1 changed! (aka a changed)
            // newValue is the observable int value (it's the same as a1.getValue())
            Log.d(Frag1.class.getSimpleName(), "a1 has changed, new value:"+ (int) newValue);
        }
    };

    public Frag1() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            // Get ObservableInteger created in activity
            a1 = (ObservableInteger) getArguments().getSerializable(PARAM);
            // Add listener for value change
            a1.addObserver(a1Changed);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }
}

I try to name my variables the same as yours, I hope it will help you.

Work with observable data objects, Here is a simple example with an Activity and a single Fragment but it will be the same with other fragments. First you need to create a class standing for the  Observability refers to the capability of an object to notify others about changes in its data. The Data Binding Library allows you to make objects, fields, or collections observable. Any plain-old object can be used for data binding, but modifying the object doesn't automatically cause the UI to update.

Using Observable in Android, For example, widgets in SWT and Android have to be updated from the UI thread and reactive programming provides ways to run observables  How to use Observable class in Android DataBinding. In this android programming source code example, we are going to use Observable class in Android DataBinding. You can copy and adopt this source code example to your android project without reinventing the wheel. Below is a step by step source code to use Observable class in Android DataBinding. If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Reactive is not part of Android but you are probably looking for this library: https://github.com/JakeWharton/RxBinding

The landing page is missing an introductory example, so you have to look at the javadoc. This post should give you a good start: How to create an Observable from OnClick Event Android? Here is the code sample from Matt to get you started

RxView.clicks(myButton)
    .subscribe(new Action1<Void>() {
        @Override
        public void call(Void aVoid) {
            /* do something */
        }
    });

Using RxJava 2 - Tutorial, ") changes, all of the other objects ("observers") that depend on it are notified. The users in this case are observers. A typical use case of Single observable would be when we make a network call in Android and receive a response. Sample Implementation: The below code always emits a Single user object. We use a Single Observable and a Single Observer. The Single Observer always emits only once so there is no onNext () .

Android now offers ViewModels with LiveData for your purpose. A view model is bound to an object with a lifecycle (Fragment, Activity) and lives as long as this object. In your case you would create a view model bound to the actvity which is accessible by all fragments.

From the Android documentation:

It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of master-detail fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item. This case is never trivial as both fragments need to define some interface description, and the owner activity must bind the two together. In addition, both fragments must handle the scenario where the other fragment is not yet created or visible.

This common pain point can be addressed by using ViewModel objects. These fragments can share a ViewModel using their activity scope to handle this communication

To use a view model for sharing data between fragments you need to:

  1. create a view model which inherits from ViewModel() and contains MutableLiveData-fields
  2. access the view model from the fragments by calling ViewModelProviders.of(activity).get(YourViewModel::class.java)
  3. change values of the view model by calling setValue for the MutableLiveData-fields
  4. register on changes of the MutableLiveData-fields by calling .observe()

Here is the central code snippet from the Android documentation on how to use ViewModels for a master-detail-view:

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class MasterFragment : Fragment() {
    private lateinit var itemSelector: Selector
    private lateinit var model: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        model = activity?.run {
            ViewModelProviders.of(this).get(SharedViewModel::class.java)
        } ?: throw Exception("Invalid Activity")
        itemSelector.setOnClickListener { item ->
        // Update the UI
        }
    }
}

class DetailFragment : Fragment() {
    private lateinit var model: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        model = activity?.run {
            ViewModelProviders.of(this).get(SharedViewModel::class.java)
        } ?: throw Exception("Invalid Activity")
        model.selected.observe(this, Observer<Item> { item ->
            // Update the UI
        })
    }
}

Android Design Patterns: The Observer Pattern, , they need to subscribe first. The instance created after subscribing in RxJava2 is called Disposable . Completable observable won’t emit any data instead it notifies the status of the task either success or failure. This observable can be used when you want to perform some task and not expect any value. A use case would be updating some data on the server by making PUT request.

RxJava Observables and Observers, development. It's touted as the go-to framework for simplifying concurrency/asynchronous tasks inherent in mobile programming. import android.os.Handler; import java.util.Observable; public class UserDataRepository extends Observable { private String mFullName; private int mAge; private static UserDataRepository INSTANCE = null; private UserDataRepository() { getNewDataFromRemote(); } // Returns a single instance of this class, creating it if necessary.

Introduction to RxJava for Android, We use a Maybe Observable and a Maybe Observer. Again we are using the same scenario as above: creating a new User. Completable. onSubscribe (): This method is invoked when the Observer is subscribed to the Observable. onNext (): This method is called when a new item is emitted from the Observable. onError (): This method is called when an error occurs and the emission of data is not successfully completed. onComplete ():

How to build Angular App with Observable Data Services, This operator creates an Observable from scratch by calling observer methods programmatically. An emitter is provided through which we can  Reactive Programming with Kotlin for Android. And we can enjoy even the function extensions, such as toObservable (it converts a list into an observable). Rx in Android.

Comments
  • You can use either Java's Observable as per the docs you've linked to or implement your own. Personally I recommend to use your own implementation of the pattern in order to learn it well. There are tons of tutorials on the net about using it. If it helps, you might look this answer of mine where I tried to explain it as simple as I could :)
  • Of course there are tutorials online, but the problem with them is that they usually refer to certain cases that are not required. Am sure if I sit for half a day tracing it out, I would get the Answer. But since I cannot right now, I asked for a simpler example on its implementation. It'll certainly help others who too like me don't want to go through the whole thing just yet and are looking for a simpler explanation for Android behavior with Observables.
  • Nice example. Few doubts there. What if the observable had another int into called 'b' and you needed that observed along with 'a'. And what is the use of serializable?
  • If your Observable object has multiple properties you can create getter/setter for each of them and add a call to notifyObservers() in setters, it will tell to every Observer that object has changed (but not which property). Serializable is only here to pass data from Activity to Fragment using a Bundle with putSerializable method.
  • @KaushikNP, if my answer fits your needs do not forget to accept it ;)
  • Sorry, checked in now. Of course, the bounty goes to you, and the answer was good, but other answers may show up and it is for the larger audience too.
  • Hello, I was following your code but have to extend this a little bit. What if ObservableInteger has got another field which is class let say ObservableCharacter. I want to observe this one and notify the main class about changes in ObservableCharacter. How can I make the correct notification?
  • Is observer pattern may help in below situation (explained in question)? stackoverflow.com/questions/47448453/…
  • Um, sorry if the question was misleading, but I want a totally local Observable implementation, not having to use RxJS or any other integration with it. Observables are provided in Android too, as seen in the link in the question above.
  • Well, my thinking was biased, I was doing to much Reactive lately ;-) Java Observables are a simple implementation of the GoF-Observer pattern, while RxJS-Observables are an implementation of the Reactive paradigm. There is a Java equivalent to RxJS which is RxJava.