RxJava. Sequential execution

后端 未结 4 1343
旧巷少年郎
旧巷少年郎 2021-02-05 11:44

In my Android App I have a presenter which handles user interactions, contains kind of request manager and if needed sends user input over request manager to request manager.

4条回答
  •  名媛妹妹
    2021-02-05 12:04

    For this kind of behaviour I'm using Flowable backpressure implementation. Create outer stream that is parent for your api request stream, flatMap the api request with maxConcurrency = 1 and implement some sort of buffer strategy, so your Flowable doesn't throw exception.

    Flowable.create(emitter -> {/* user input stream*/}, BackpressureStrategy.BUFFER)
                    .onBackpressureBuffer(127, // buffer size
                            () -> {/* overflow action*/},
                            BackpressureOverflowStrategy.DROP_LATEST) // action when buffer exceeds 127
                    .flatMap(request -> sendRequest(request), 1) // very important parameter
                    .subscribe(results -> {
                        // work with results
                    }, error -> {
                        // work with errors
                    });
    

    It will buffer user input up to given threshold, and then drop it(if you don't do this it will throw exception, but it is highly unlikely that user will exceed such buffer), it will execute sequentially 1 by 1 like a queue. Don't try to implement this behaviour yourself if there are operators for thing kind of behaviour in libary itself.

    Oh I forgot to mention, your sendRequest() method must return Flowable or you can convert it to Flowable.

    Hope this helps!

提交回复
热议问题