简体   繁体   中英

Do something with the data “read only” using observable thread in RxJava

I wonder how can I do something with the data that a Observable is emitting in the Observable's thread, without changing the data. For example, I request a list of task from a sever and print them out

    //Assume that taskService.getTasks returns an Observable<List<Task>>
    Observable<List<Task>> observable = taskService.getTasks(...).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulars.mainThread());
    observable.subscribe(tasks -> {
        for(Task task: tasks) System.out.println(task);
    });

But then I want to save the task list to the disk as cache. How can I use operator to make this happen in the subscription thread? I found similar operators like map , but then I have to return the task list after I done saving to disk:

    Observable<List<Task>> observable = taskService.getTasks(...).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    observable.map(tasks1 -> {
        saveToDisk(tasks1); 
        return tasks1;      //Here, I have to return the tasks
    }); 
    observable.subscribe(tasks -> {
        for(Task task: tasks) System.out.println(task);
    });

Essentially map was intended to transform the data in one way or another. In this case, I just want to save the tasks to the disk without changing anything of it. map was not built for this, and also, the return statement in map is redundant. I also find doOnNext or doOnEach that does what I want, but theses two operators run the code in observer's thread. In the above example, that is the android's main thread. That is also not good. Is there any way to so

I think the following should run the saveToDisk on the background thread:

Observable<List<Task>> observable = taskService.getTasks(...)
    .doOnNext(tasks1 -> {
         saveToDisk(tasks1)
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread());

observable.subscribe(tasks -> {
    for(Task task: tasks) System.out.println(task);
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM