Error-Handling Operators
Say we were to implement an image store such that when a request comes in it will first check if
the image is cached, and if so, return the image from the cache, otherwise, return fetch image over
the network.
1
public class
ImageStore
{
2
3
private
ImageStoreCache cache
=
new
ImageStoreCache
();
4
5
public
Observable
<
Bitmap
>
getImage
(
String filename
) {
6
return
cache
.
getImage
(
filename
);
7
}
8
}
9
10
public class
ImageStoreCache
{
11
12
private
LruCache
<
String
,
Bitmap
>
cache
=
new
LruCache
<>(100);
13
14
public
Observable
<
Bitmap
>
getImage
(
String filename
) {
15
return
Observable
.
fromCallable
(() -> {
16
Bitmap cachedBitmap
=
cache
.
get
(
filename
);
17
if
(
cachedBitmap
!=
null
) {
18
return
cachedBitmap
;
19
}
20
throw new
ImageNotInCacheException
();
21
});
22
}
23
24
25
public
void
addImage
(
String filename
,
Bitmap bitmap
) {
26
cache
.
put
(
filename
,
bitmap
);
27
}
28
}
29
30
public class
ImageNotInCacheException
extends
Exception
{
31
}
Chapter 7: Error Handling
95
ImageStore
so far will simply request the image from the
ImageStoreCache
and will not yet make
a network call if an image does not exist in the cache. Instead, it will return the
ImageNotInCache-
Exception
to the Observer’s
.onError()
method. To handle the case of fetching an image over the
network, we can make use of any of the following error-handling operators:
Observable.onErrorReturnItem(), Observable.onErrorReturn()
and Observable.onErrorResumeNext()
•
Observable.onErrorReturnItem(T item)
: when an error is received upstream, this operator
will return the item provided to it downstream instead of the received error.
Marble diagram of .onErrorReturnItem()
•
Observable.onErrorReturn(Function super Throwable, ? extends T> valueSupplier)
:
when an error is received upstream, this operator will invoke the function provided and return
the result of that function downstream instead of the received error. This operator is preferred
if you want to return a different item depending on the error.
Chapter 7: Error Handling
96
Marble diagram of .onErrorReturn()
•
Observable.onErrorResumeNext(ObservableSource extends T> next))
: similar to
.on-
ErrorReturnItem()
but instead of returning an item, it will pass control to the provided
Observable
instead of passing the received error.
Marble diagram of .onErrorResumeNext()
In our case, we will make use of
.onErrorResumeNext()
to return an
Observable
when an
ImageNotInCacheException
error is received.
Chapter 7: Error Handling
97
1
Do'stlaringiz bilan baham: |