11

Suppose we are getting a generic Object from SharedPrefs using .create():

return Observable.create(subscriber -> {
      String json = sharedPreferences.getString(key, "");
      T myClass = gson.fromJson(json, generic);
      subscriber.onNext(myClass);
      subscriber.onComplete();
    });

and using .fromCallable():

return Observable.fromCallable(() -> {
      String json = sharedPreferences.getString(key, "");
      return gson.fromJson(json, generic);
    });

Is there any Difference if we call onComplete() immediately after first emmit from Observable.create() and using Observable.fromCallable()? If so, what are the pros/cons?

hrskrs
  • 4,447
  • 5
  • 38
  • 52

1 Answers1

16

Observable.create let's you emit multiple items while fromCallable emits only a single item.

You should use the latter as it is more expressive about the intent of having a single element sequence and has a slighly lower overhead.

Drawback is that you can't have an async single element source with it whereas create let's you delay the call to onNext to a later point in time.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • Can you specify a more descriptive answer with examples to understand it more. – Sri Krishna Sep 17 '19 at 16:26
  • 2
    Please be more proactive and check the available RxJava documents and [wiki](https://github.com/ReactiveX/RxJava/wiki/Creating-Observables). – akarnokd Sep 18 '19 at 09:44