RxJava中doOnComplete执行时机及字段赋值可靠性确认
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:
- Calling
setSomeFieldCompletable(entity)gives you a Completable chain, but none of the code inside it runs yet (RxJava is lazy by default). - The
andThen()operator is designed to wait for the upstream Completable to fully complete before moving on to the next stream (the Single fromdefer). - When the Completable finally executes (after subscription), here’s the order:
- First,
loadSomeValueFromDbSingle(entity.id)runs and fetches the value from the database. - Next,
doOnSuccessfires, settingentity.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.
- First,
- Only once all those steps are finished does
andThentrigger theSingle.defer()lambda. At that point,entity.isInithas already been set totrue.
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

