You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RxJava中doOnComplete执行时机及字段赋值可靠性确认

Answers to Your RxJava Questions

1. Does doOnComplete() run before the method returns?

Short answer: No, and it’s important to understand why.

When you write a method that returns a Completable (like your setSomeFieldCompletable), the method itself returns immediately with the Completable instance—before any of the stream’s operations (including doOnComplete()) actually run.

doOnComplete() is a side-effect operator that only executes when the Completable stream successfully finishes its work. That happens later, when someone subscribes to the Completable and the upstream tasks (like your database load) complete. If you never subscribe to the Completable, doOnComplete() will never run at all. Even if you do subscribe, the method will have already returned long before doOnComplete() executes—unless you use a blocking operator like blockingAwait() to force the method to wait for the stream to finish.

2. Will entity.isInit be true in the andThen block?

Absolutely—you can count on entity.isInit == true when the Single.defer() lambda runs. Here’s the play-by-play of how the execution flows:

  1. Calling setSomeFieldCompletable(entity) gives you a Completable chain, but none of the code inside it runs yet (RxJava is lazy by default).
  2. The andThen() operator is designed to wait for the upstream Completable to fully complete before moving on to the next stream (the Single from defer).
  3. When the Completable finally executes (after subscription), here’s the order:
    • First, loadSomeValueFromDbSingle(entity.id) runs and fetches the value from the database.
    • Next, doOnSuccess fires, setting entity.value = value.
    • toCompletable() converts the successful Single into a Completable that signals it’s done.
    • Right after that, doOnComplete(() -> entity.isInit = true) runs—it’s part of the Completable’s completion sequence.
  4. Only once all those steps are finished does andThen trigger the Single.defer() lambda. At that point, entity.isInit has already been set to true.

Just to be clear: This guarantee holds even if parts of the stream run on different threads—andThen() always waits for the upstream stream to fully complete, regardless of thread scheduling.


内容的提问来源于stack exchange,提问作者Alex Kokorin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:28:07