Hi, I try ti use `Single<T>.doOnAfterSuccess...
# reaktive
l
Hi, I try ti use
Single<T>.doOnAfterSuccess
, as doc says
Calls the action with the emitted value when the Single signals onSuccess. The action is called after the observer is called.
but my action is called first, before onSuccess in subscriber. what can be wrong?
a
l
I had next code
Copy code
singleOf(getState().check(intent.words))
                        .subscribeOn(mainScheduler)
                        .map { acceptedWords -> return@map (getState().acceptedWords + acceptedWords) }
                        .doOnAfterSuccess { if (getState().goalCount <= it.size) publish(TrainingStore.Label.Complete) }
                        .map { acceptedWords -> Result.Accepted(acceptedWords) }
                        .observeOn(mainScheduler)
                        .subscribeScoped(
                            isThreadLocal = true,
                            onSuccess = { result -> dispatch(result) }
                        )
and I receive Complete label before I receive result from onSuccess
but sorry, problem is in the lambda, which is return wrong state
a
This is expected. You have
observeOn
before
subscribe
and so
onSuccess
call is scheduled asynchronously.
doOnAfterSuccess
is called after
map
below it, but before
onSuccess
, which is scheduled.
l
hm… thx, but it is not obviously for me 😞
when I removed observeOn it is help
thx a lot 🙂
a
It might not be very obvious indeed. As mentioned in the docs, the operator's callback is called after the observer's
onSuccess
. In this case the observer is the
map
operator below it.
l
is it happing because we have observeOn operator?
because I tried to move doOnAfterSuccess after map operator, it was not help
a
By default all operators are synchronous, only those which accept
Scheduler
can do something asynchronously. So when
doOnAfterSuccess
's upstream signals
onSuccess
, the value is received by
doOnAfterSuccess
, which firstly calls its downstream
Observer
(in this case it is the
map
operator right below), and when the call returns the
doOnAfterSuccess
callback is called. What happens in the downstream: • the
map
operator receives the
onSuccess
value, maps it with the provided
mapper
function and calls its downstream
Observer
- the
observerOn
operator below the
map
operator, which is below the
doOnAfterSuccess
operator • the
observeOn
operator schedules
onSuccess
emission via the provided
Scheduler
and returns the
onSuccess
call • the
map
operator also returns the
onSuccess
call • the
doOnAfterSuccess
operator now calls the callback • the
subscribe-onSuccess
below
observeOn
is called at some point later. Since in the provided call everything runs on the main thread, the
subscribe/onSuccess
will be called only when the wlole chain is finished, and so the main thread unblocked. In case of different schedulers, the
subscribe/onSuccess
would be called concurrently.
l
Thx for describing:)
👍 1