Reputation: 3527
I have defined and interface, with an endpoint that returns JSON. Retrofit converts this JSON into MyObject. It could be also a list, map, etc, it doesn't matter now.
This is how I subscribe.
subscription = Retrofit.create(MyApi.class)
.doSomething()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<MyObject>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(MyObject myObject) {
}
});
My question is:
Is it possible that onNext is called more than once? If yes, in which occasion?
Upvotes: 1
Views: 601
Reputation: 394
If your retrofit returns an array/list of data, onNext is called multiple times. But if your retrofit returns a single data objext, onNext will be called only once. Example:
//POJO
class User {
int userId;
String UserName;
}
//POJO
class UserData {
List<User> users;
}
interface RetrofitGithub {
@GET("...")
Observable<List<User>> getUsers();
@GET("...")
Observable<UserData> getUserData();
}
If you subscribe to getUsers() onNext will be called multiple N times.(N = size of the list)
If you subscribe to getUserData() onNext will be called only once.
Upvotes: 0
Reputation: 9569
In your case, no it's impossible, of course if you do not emit more items in doSomething()
method.
But there is another, quite usual cases, for instance, if you use Local first
approach and subscribing on hot
observable which will emit new item each time when data in data base has change.
E.g. using retrofit:
@Override
public Observable<List<FollowMeUser>> getFollowMeUsers() {
return realm.where(FollowMeUser.class)
.findAll()
.asObservable()
.filter(RealmResults::isLoaded);
}
getFollowMeUsers()
.subscribe(users -> {Timber.d("saved data has changed")}, Timber::e);
Each time when you will insert/modify/delete FollowMeUser
collection, all subscribers of getFollowMeUsers
will be notified.
Upvotes: 1