简体   繁体   中英

RxJava - Multiple tasks in a observable

I have a list that contain many objects and i will use it as observable, Each object has two url, In each consuming, I should ensure both url downloaded successfully, If one of url did not downloaded, RxJava should be stop the job, I am new in RxJava and i can just do simple works.

This is my object

public class mediaChunk
{
    public String audioChunkUrl;
    public String videoChunkUrl;
}

List<mediaChunk> list = new ArrayList<>();

one approach would be:

  1. use the Observable.fromIterable factory method to setup the stream from the initial List<MediaChunk>
  2. flatMap each emission from that stream and use the Observable.just factory method to create a stream of audio + video URLs from each MediaChunk instance

the result is a flattened stream of URLs for which subscribers can plug in their own onNext , onError , and onComplete handlers.

the code would look something like this:

Observable.fromIterable(
        Arrays.asList(
            new MediaChunk("audio-1", "video-1"),
            new MediaChunk("audio-2", "video-2"),
            new MediaChunk("audio-3", "video-3")
        ))
        .flatMap(chunk -> Observable.just(chunk.audioChunkUrl, chunk.videoChunkUrl))
        .subscribe(
            value -> {
              System.out.println("## onNext(" + value + ")");
            },
            error -> {
              System.out.println("## onError(" + error.getMessage() + ")");
            },
            () -> {
              System.out.println("## onComplete()");
            }
        );

not sure if this fits the bill, but hopefully it's enough to at least inspire some thought.

Update - example mapping emissions to Completable

Observable.fromIterable(
    Arrays.asList(
        new MediaChunk("audio-1", "video-1"),
        new MediaChunk("audio-2", "video-2"),
        new MediaChunk("audio-3", "video-3")
    ))
    .flatMap(chunk -> Observable.just(chunk.audioChunkUrl, chunk.videoChunkUrl))
    .flatMapCompletable(url -> {
      return Completable.fromCallable(() -> {
        return "## ...handling network call for [" + url + "]";
      });
    })
    .subscribe(
        () -> {
          System.out.println("## onComplete()");
        },
        error -> {
          System.out.println("## onError(" + error.getMessage() + ")");
        }
    );

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