The View Client
is very similar to the HttpClient. While the HttpClient is responsible for handling requests (views, json data, images, etc), the ViewClient
is only responsible for fetching views (Server Driven Views).
The ViewClient interface has two functions fetch
and prefetch
.
The fetch
default implementation has 2 functionalities:
HttpClient
and makes a request which returns a ResponseData.The prefetch
default implementation has 2 functionalities:
HttpClient
and make the request for a ResponseData and store it in cache (memory).fetch
just search for responses that may have been prefetched earlier, and prefetch
just store responses. It just do this, and that is enough for most applications. But some other applications may need an extra behavior when fetching views, and this is when a customized ViewClient must be made.A good example is caching. Let’s say we want to locally store a view in a way that when Beagle calls viewClient.fetch
again, it returns the cached result, instead of calling the HttpClient.
To do this, we can create a **MyViewClient**
class that implements ViewClient
, has a storage and is annotated with @BeagleComponent
as follows:
@BeagleComponent
class MyViewClient(
private val httpClient: HttpClient? = BeagleEnvironment.beagleSdk.httpClientFactory?.create(),
private val cachedResponses: MutableMap<String, ResponseData> = mutableMapOf()
) : ViewClient {
override fun fetch(requestData: RequestData, onSuccess: OnSuccess, onError: OnError): RequestCall? {
val cachedResponse = cachedResponses[requestData.url]
return if (cachedResponse != null) {
onSuccess(cachedResponse)
null
} else {
requestData.doRequest(httpClient, onSuccess = { response ->
onSuccess(response)
cachedResponses[requestData.url] = response
}, onError)
}
}
override fun prefetch(requestData: RequestData, onSuccess: OnSuccess, onError: OnError): RequestCall? {
val cachedResponse = cachedResponses[requestData.url]
return if (cachedResponse != null) {
onSuccess(cachedResponse)
null
} else {
requestData.doRequest(httpClient, onSuccess = { response ->
onSuccess(response)
cachedResponses[requestData.url] = response
}, onError)
}
}
companion object {
internal val instance = MyViewClient()
}
}
Above we have implemented a logic to fetch
and prefetch
that will store every fetch result in memory using a MutableMap called cachedResponses
. It uses the request url as key, and searches for a ResponseData
in it every time fetch
or prefetch
is called. This is a simple implementation, since this cache would never expire, and the objective here is to show how this feature could be implemented using the ViewClient.
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.