I was just making simple Notes app in order to understand Room and Rxjava (and java).
Entity
@Entity
public class Notes {
@PrimaryKey(autoGenerate = true)
public long id;
String title;
String notes;}
Dao
@Query("SELECT * FROM Notes")
Flowable<List<OnlyNotes>> getAllNotes();
public class OnlyNotes {
String notes;
}
MainActivity:
static List<String> notes;
public Flowable<List<NotesDao.OnlyNotes>> initialize(){
return (Flowable<List<NotesDao.OnlyNotes>>) notesDao.getAllNotes()
.observeOn(AndroidSchedulers.mainThread());
}
onCreate()
notes = (List<String>) initialize();//for RecyclerViewAdapter
FATAL EXCEPTION: main
Caused by: java.lang.ClassCastException: io.reactivex.internal.operators.flowable.FlowableObserveOn cannot be cast to java.util.List
Can you please explain me what is wrong with my code and what's the best practice of doing what I'm trying to do? I will be glad to any answer.
Replace Flowable<> with Observable<> in Dao and use code below. For Flowable you have to use Subscriber inside subscribe() method and override its methods. this hopefully should clarify your understanding of rxjava if you skipped some topics as I did.
db.notesDao().getAllNotes().subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<NotesDao.OnlyNotes>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onNext(@NonNull List<NotesDao.OnlyNotes> onlyNotes) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notes.addAll(onlyNotes.stream().map(objects -> objects.notes).collect(Collectors.toList()));
}else {
for (NotesDao.OnlyNotes onlyNotes1 : onlyNotes) {
notes.add(onlyNotes1.notes);
}
}
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.