Difference between Observable.create() and Observable.fromCallable()

£可爱£侵袭症+ 提交于 2019-12-04 19:16:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43785961/difference-between-observable-create-and-observable-fromcallable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!