Reputation: 37121
Suppose I have some process, such as downloading a file or running a big computation.
The events it fires might look like this:
{ progress: "0%" }
{ progress: "23%" }
{ progress: "78%" }
{ progress: "100%" }
{ content: "Hello. world. " }
Or perhaps:
{ progress: "0%" }
{ progress: "23%" }
{ error: "Access denied. " }
In each case, we have n
status-updates (T
) followed by either a result (S
) or an error (Throwable
):
T* ( S | Throwable )
A process is a mix of Observable<T>
and Single<S>
.
There are a few ways to model a process using the Rx primitives:
Observable<T>
and Single<S>
Observable<Either<T, S>>
Observable<Object>
with instanceof
calls for castingProcess<T, S>
with toObservable
and toSingle
methodsHow has this been successfully modelled in the past?
Which approaches are best and when should they be used?
Upvotes: 0
Views: 54
Reputation: 8227
Let us rule out the Object
plus instanceof
right away. This is the certain road to madness.
It will depend on how you are going to use the T
and S
results. I believe that T
should be a container of S
.
class T<S> {
public boolean isSuccess() { ... }
public boolean isStatus() { ... }
public Status getStatus() { ... }
public S getResult() { ... }
}
The initial stream of emitted values have simply the status values (progress amounts), while the last item in the stream carries the S
value.
If you need S
to be a Single
, then
observable
.filter( t -> t.isSuccess() )
.last()
.map( t -> t.getResult() )
.toSingle()
will be adequate. If you need the status reports to appear elsewhere then use
observable.filter( t-> t.isStatus() )
This gives you your
Upvotes: 1