| 1 |
/* |
| 2 |
* Copyright (c) 2016-present, RxJava Contributors. |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in |
| 5 |
* compliance with the License. You may obtain a copy of the License at |
| 6 |
* |
| 7 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
* |
| 9 |
* Unless required by applicable law or agreed to in writing, software distributed under the License is |
| 10 |
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See |
| 11 |
* the License for the specific language governing permissions and limitations under the License. |
| 12 |
*/ |
| 13 |
|
| 14 |
package io.reactivex.rxjava3.internal.schedulers; |
| 15 |
|
| 16 |
import java.util.concurrent.TimeUnit; |
| 17 |
import java.util.concurrent.atomic.*; |
| 18 |
|
| 19 |
import io.reactivex.rxjava3.annotations.NonNull; |
| 20 |
import io.reactivex.rxjava3.core.*; |
| 21 |
import io.reactivex.rxjava3.disposables.*; |
| 22 |
import io.reactivex.rxjava3.functions.Function; |
| 23 |
import io.reactivex.rxjava3.internal.util.ExceptionHelper; |
| 24 |
import io.reactivex.rxjava3.processors.*; |
| 25 |
|
| 26 |
/** |
| 27 |
* Allows the use of operators for controlling the timing around when actions |
| 28 |
* scheduled on workers are actually done. This makes it possible to layer |
| 29 |
* additional behavior on this {@link Scheduler}. The only parameter is a |
| 30 |
* function that flattens an {@link Observable} of {@link Observable} of |
| 31 |
* {@link Completable}s into just one {@link Completable}. There must be a chain |
| 32 |
* of operators connecting the returned value to the source {@link Observable} |
| 33 |
* otherwise any work scheduled on the returned {@link Scheduler} will not be |
| 34 |
* executed. |
| 35 |
* <p> |
| 36 |
* When {@link Scheduler#createWorker()} is invoked a {@link Observable} of |
| 37 |
* {@link Completable}s is onNext'd to the combinator to be flattened. If the |
| 38 |
* inner {@link Observable} is not immediately subscribed to an calls to |
| 39 |
* {@link Worker#schedule} are buffered. Once the {@link Observable} is |
| 40 |
* subscribed to actions are then onNext'd as {@link Completable}s. |
| 41 |
* <p> |
| 42 |
* Finally the actions scheduled on the parent {@link Scheduler} when the inner |
| 43 |
* most {@link Completable}s are subscribed to. |
| 44 |
* <p> |
| 45 |
* When the {@link io.reactivex.rxjava3.core.Scheduler.Worker Worker} is unsubscribed the {@link Completable} emits an |
| 46 |
* onComplete and triggers any behavior in the flattening operator. The |
| 47 |
* {@link Observable} and all {@link Completable}s give to the flattening |
| 48 |
* function never onError. |
| 49 |
* <p> |
| 50 |
* Limit the amount concurrency two at a time without creating a new fix size |
| 51 |
* thread pool: |
| 52 |
* |
| 53 |
* <pre> |
| 54 |
* {@code |
| 55 |
* Scheduler limitScheduler = Schedulers.computation().when(workers -> { |
| 56 |
* // use merge max concurrent to limit the number of concurrent |
| 57 |
* // callbacks two at a time |
| 58 |
* return Completable.merge(Observable.merge(workers), 2); |
| 59 |
* }); |
| 60 |
* } |
| 61 |
* </pre> |
| 62 |
* <p> |
| 63 |
* This is a slightly different way to limit the concurrency but it has some |
| 64 |
* interesting benefits and drawbacks to the method above. It works by limited |
| 65 |
* the number of concurrent {@link io.reactivex.rxjava3.core.Scheduler.Worker Worker}s rather than individual actions. |
| 66 |
* Generally each {@link Observable} uses its own {@link io.reactivex.rxjava3.core.Scheduler.Worker Worker}. This means |
| 67 |
* that this will essentially limit the number of concurrent subscribes. The |
| 68 |
* danger comes from using operators like |
| 69 |
* {@link Flowable#zip(org.reactivestreams.Publisher, org.reactivestreams.Publisher, io.reactivex.rxjava3.functions.BiFunction)} where |
| 70 |
* subscribing to the first {@link Observable} could deadlock the subscription |
| 71 |
* to the second. |
| 72 |
* |
| 73 |
* <pre> |
| 74 |
* {@code |
| 75 |
* Scheduler limitScheduler = Schedulers.computation().when(workers -> { |
| 76 |
* // use merge max concurrent to limit the number of concurrent |
| 77 |
* // Observables two at a time |
| 78 |
* return Completable.merge(Observable.merge(workers, 2)); |
| 79 |
* }); |
| 80 |
* } |
| 81 |
* </pre> |
| 82 |
* |
| 83 |
* Slowing down the rate to no more than than 1 a second. This suffers from the |
| 84 |
* same problem as the one above I could find an {@link Observable} operator |
| 85 |
* that limits the rate without dropping the values (aka leaky bucket |
| 86 |
* algorithm). |
| 87 |
* |
| 88 |
* <pre> |
| 89 |
* {@code |
| 90 |
* Scheduler slowScheduler = Schedulers.computation().when(workers -> { |
| 91 |
* // use concatenate to make each worker happen one at a time. |
| 92 |
* return Completable.concat(workers.map(actions -> { |
| 93 |
* // delay the starting of the next worker by 1 second. |
| 94 |
* return Completable.merge(actions.delaySubscription(1, TimeUnit.SECONDS)); |
| 95 |
* })); |
| 96 |
* }); |
| 97 |
* } |
| 98 |
* </pre> |
| 99 |
* <p>History 2.0.1 - experimental |
| 100 |
* @since 2.1 |
| 101 |
*/ |
| 102 |
public class SchedulerWhen extends Scheduler implements Disposable { |
| 103 |
private final Scheduler actualScheduler; |
| 104 |
private final FlowableProcessor<Flowable<Completable>> workerProcessor; |
| 105 |
private Disposable disposable; |
| 106 |
|
| 107 |
public SchedulerWhen(Function<Flowable<Flowable<Completable>>, Completable> combine, Scheduler actualScheduler) { |
| 108 |
this.actualScheduler = actualScheduler; |
| 109 |
// workers are converted into completables and put in this queue. |
| 110 |
this.workerProcessor = UnicastProcessor.<Flowable<Completable>>create().toSerialized(); |
| 111 |
// send it to a custom combinator to pick the order and rate at which |
| 112 |
// workers are processed. |
| 113 |
try { |
| 114 |
disposable = combine.apply(workerProcessor).subscribe(); |
| 115 |
} catch (Throwable e) { |
| 116 |
throw ExceptionHelper.wrapOrThrow(e); |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
@Override |
| 121 |
public void dispose() { |
| 122 |
disposable.dispose(); |
| 123 |
} |
| 124 |
|
| 125 |
@Override |
| 126 |
public boolean isDisposed() { |
| 127 |
return disposable.isDisposed(); |
| 128 |
} |
| 129 |
|
| 130 |
@NonNull |
| 131 |
@Override |
| 132 |
public Worker createWorker() { |
| 133 |
final Worker actualWorker = actualScheduler.createWorker(); |
| 134 |
// a queue for the actions submitted while worker is waiting to get to |
| 135 |
// the subscribe to off the workerQueue. |
| 136 |
final FlowableProcessor<ScheduledAction> actionProcessor = UnicastProcessor.<ScheduledAction>create().toSerialized(); |
| 137 |
// convert the work of scheduling all the actions into a completable |
| 138 |
Flowable<Completable> actions = actionProcessor.map(new CreateWorkerFunction(actualWorker)); |
| 139 |
|
| 140 |
// a worker that queues the action to the actionQueue subject. |
| 141 |
Worker worker = new QueueWorker(actionProcessor, actualWorker); |
| 142 |
|
| 143 |
// enqueue the completable that process actions put in reply subject |
| 144 |
workerProcessor.onNext(actions); |
| 145 |
|
| 146 |
// return the worker that adds actions to the reply subject |
| 147 |
return worker; |
| 148 |
} |
| 149 |
|
| 150 |
static final Disposable SUBSCRIBED = new SubscribedDisposable(); |
| 151 |
|
| 152 |
static final Disposable DISPOSED = Disposable.disposed(); |
| 153 |
|
| 154 |
@SuppressWarnings("serial") |
| 155 |
abstract static class ScheduledAction extends AtomicReference<Disposable> implements Disposable { |
| 156 |
ScheduledAction() { |
| 157 |
super(SUBSCRIBED); |
| 158 |
} |
| 159 |
|
| 160 |
void call(Worker actualWorker, CompletableObserver actionCompletable) { |
| 161 |
Disposable oldState = get(); |
| 162 |
// either SUBSCRIBED or UNSUBSCRIBED |
| 163 |
if (oldState == DISPOSED) { |
| 164 |
// no need to schedule return |
| 165 |
return; |
| 166 |
} |
| 167 |
if (oldState != SUBSCRIBED) { |
| 168 |
// has already been scheduled return |
| 169 |
// should not be able to get here but handle it anyway by not |
| 170 |
// rescheduling. |
| 171 |
return; |
| 172 |
} |
| 173 |
|
| 174 |
Disposable newState = callActual(actualWorker, actionCompletable); |
| 175 |
|
| 176 |
if (!compareAndSet(SUBSCRIBED, newState)) { |
| 177 |
// set would only fail if the new current state is some other |
| 178 |
// subscription from a concurrent call to this method. |
| 179 |
// Unsubscribe from the action just scheduled because it lost |
| 180 |
// the race. |
| 181 |
newState.dispose(); |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
protected abstract Disposable callActual(Worker actualWorker, CompletableObserver actionCompletable); |
| 186 |
|
| 187 |
@Override |
| 188 |
public boolean isDisposed() { |
| 189 |
return get().isDisposed(); |
| 190 |
} |
| 191 |
|
| 192 |
@Override |
| 193 |
public void dispose() { |
| 194 |
getAndSet(DISPOSED).dispose(); |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
@SuppressWarnings("serial") |
| 199 |
static class ImmediateAction extends ScheduledAction { |
| 200 |
private final Runnable action; |
| 201 |
|
| 202 |
ImmediateAction(Runnable action) { |
| 203 |
this.action = action; |
| 204 |
} |
| 205 |
|
| 206 |
@Override |
| 207 |
protected Disposable callActual(Worker actualWorker, CompletableObserver actionCompletable) { |
| 208 |
return actualWorker.schedule(new OnCompletedAction(action, actionCompletable)); |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
@SuppressWarnings("serial") |
| 213 |
static class DelayedAction extends ScheduledAction { |
| 214 |
private final Runnable action; |
| 215 |
private final long delayTime; |
| 216 |
private final TimeUnit unit; |
| 217 |
|
| 218 |
DelayedAction(Runnable action, long delayTime, TimeUnit unit) { |
| 219 |
this.action = action; |
| 220 |
this.delayTime = delayTime; |
| 221 |
this.unit = unit; |
| 222 |
} |
| 223 |
|
| 224 |
@Override |
| 225 |
protected Disposable callActual(Worker actualWorker, CompletableObserver actionCompletable) { |
| 226 |
return actualWorker.schedule(new OnCompletedAction(action, actionCompletable), delayTime, unit); |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
static class OnCompletedAction implements Runnable { |
| 231 |
final CompletableObserver actionCompletable; |
| 232 |
final Runnable action; |
| 233 |
|
| 234 |
OnCompletedAction(Runnable action, CompletableObserver actionCompletable) { |
| 235 |
this.action = action; |
| 236 |
this.actionCompletable = actionCompletable; |
| 237 |
} |
| 238 |
|
| 239 |
@Override |
| 240 |
public void run() { |
| 241 |
try { |
| 242 |
action.run(); |
| 243 |
} finally { |
| 244 |
actionCompletable.onComplete(); |
| 245 |
} |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
static final class CreateWorkerFunction implements Function<ScheduledAction, Completable> { |
| 250 |
final Worker actualWorker; |
| 251 |
|
| 252 |
CreateWorkerFunction(Worker actualWorker) { |
| 253 |
this.actualWorker = actualWorker; |
| 254 |
} |
| 255 |
|
| 256 |
@Override |
| 257 |
public Completable apply(final ScheduledAction action) { |
| 258 |
return new WorkerCompletable(action); |
| 259 |
} |
| 260 |
|
| 261 |
final class WorkerCompletable extends Completable { |
| 262 |
final ScheduledAction action; |
| 263 |
|
| 264 |
WorkerCompletable(ScheduledAction action) { |
| 265 |
this.action = action; |
| 266 |
} |
| 267 |
|
| 268 |
@Override |
| 269 |
protected void subscribeActual(CompletableObserver actionCompletable) { |
| 270 |
actionCompletable.onSubscribe(action); |
| 271 |
action.call(actualWorker, actionCompletable); |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
static final class QueueWorker extends Worker { |
| 277 |
private final AtomicBoolean unsubscribed; |
| 278 |
private final FlowableProcessor<ScheduledAction> actionProcessor; |
| 279 |
private final Worker actualWorker; |
| 280 |
|
| 281 |
QueueWorker(FlowableProcessor<ScheduledAction> actionProcessor, Worker actualWorker) { |
| 282 |
this.actionProcessor = actionProcessor; |
| 283 |
this.actualWorker = actualWorker; |
| 284 |
unsubscribed = new AtomicBoolean(); |
| 285 |
} |
| 286 |
|
| 287 |
@Override |
| 288 |
public void dispose() { |
| 289 |
// complete the actionQueue when worker is unsubscribed to make |
| 290 |
// room for the next worker in the workerQueue. |
| 291 |
if (unsubscribed.compareAndSet(false, true)) { |
| 292 |
actionProcessor.onComplete(); |
| 293 |
actualWorker.dispose(); |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
@Override |
| 298 |
public boolean isDisposed() { |
| 299 |
return unsubscribed.get(); |
| 300 |
} |
| 301 |
|
| 302 |
@NonNull |
| 303 |
@Override |
| 304 |
public Disposable schedule(@NonNull final Runnable action, final long delayTime, @NonNull final TimeUnit unit) { |
| 305 |
// send a scheduled action to the actionQueue |
| 306 |
DelayedAction delayedAction = new DelayedAction(action, delayTime, unit); |
| 307 |
actionProcessor.onNext(delayedAction); |
| 308 |
return delayedAction; |
| 309 |
} |
| 310 |
|
| 311 |
@NonNull |
| 312 |
@Override |
| 313 |
public Disposable schedule(@NonNull final Runnable action) { |
| 314 |
// send a scheduled action to the actionQueue |
| 315 |
ImmediateAction immediateAction = new ImmediateAction(action); |
| 316 |
actionProcessor.onNext(immediateAction); |
| 317 |
return immediateAction; |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
static final class SubscribedDisposable implements Disposable { |
| 322 |
@Override |
| 323 |
public void dispose() { |
| 324 |
} |
| 325 |
|
| 326 |
@Override |
| 327 |
public boolean isDisposed() { |
| 328 |
return false; |
| 329 |
} |
| 330 |
} |
| 331 |
} |