I am a bit confused about observable single object and list of objects
when i do the following with Observable> then it works
retrofit interface MainApi:
Observable<Todo> getTodos();
in activity:
mainApi.getTodos()
.subscribeOn(Schedulers.io())
.concatMap(new Function<List<Todo>, ObservableSource<Todo>>() {
@Override
public ObservableSource<Todo> apply(List<Todo> todos) throws Exception {
return Observable.fromIterable(todos).subscribeOn(Schedulers.io());
}
})
.subscribe(new Observer<Todo>() {
@Override
public void onSubscribe(Disposable d) {
Log.d("LogMe", ">>>Inside susbcribed>>>");
}
@Override
public void onNext(Todo todo) {
Log.d("LogMe", ">>>Inside onNExt>>>" + todo.getName());
}
@Override
public void onError(Throwable e) {
Log.d("LogMe", ">>>Inside onError>>>" +e.toString());
}
@Override
public void onComplete() {
Log.d("LogMe", ">>>Inside onComplete>>>");
}
});
But when use Observable then it doesnt work.
retrofit interface MainApi:
Observable<Todo> getTodos();
in activity:
mainApi.getTodos().subscribeOn(Schedulers.io())
.map(new Function<Todo, String>() {
@Override
public String apply(Todo todo) throws Exception {
return todo.getName();
}
})
.doOnNext(new Consumer<String>() {
@Override
public void accept(String stringObservable) throws Exception {
Log.d("LogMe", ">>>Inside >>> doOnNext");
}
})
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
Log.d("LogMe", ">>>Inside susbcribed>>>");
}
@Override
public void onNext(String stringObservable) {
Log.d("LogMe", ">>>Inside onNExt>>>");
}
@Override
public void onError(Throwable e) {
Log.d("LogMe", ">>>Inside onError>>>" +e.toString());
}
@Override
public void onComplete() {
Log.d("LogMe", ">>>Inside Presenter onComplete>>>");
}
});
then i get the error:
LogMe: >>>Inside Presenter onError>>>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
Where am I going wrong? If its possible to get the result with single observable then how do i iterate through each item/object of Todo?
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path
The error is from the Gson
library.
Why this Error, What this error means?
This error simply means Gson can't deserialize JSON to Java Object. because Gson is expecting a JSON object and unexpectedly it received a JSON Array from the response.
How to Fix it?
You can fix it easily by changing the return type of Observable<Todo> getTodos();
to Observable<List<Todo>> getTodos();
Hope this helps!!
Happy Coding :)