Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.
Question 1 of 60 · Retrofit Basics and Integration · Easy
What is Retrofit primarily used for in Android development?
Not quite. Try another option.
Answer: Type-safe HTTP client for Android and Java
Retrofit is a library that simplifies making network requests to web services and handling their API responses in a type-safe manner.
Question 2 of 60 · Retrofit Basics and Integration · Easy
Which company is the creator of the Retrofit library?
Not quite. Try another option.
Answer: Square
Retrofit is an open-source HTTP client library developed and maintained by Square, Inc.
Question 3 of 60 · Retrofit Basics and Integration · Easy
What is the main purpose of the Retrofit.Builder class?
Not quite. Try another option.
Answer: To construct a Retrofit instance with specific configurations
The Retrofit.Builder class uses the builder pattern to configure and create a new Retrofit instance, allowing you to set the base URL, converters, and other options.
Question 4 of 60 · Retrofit Basics and Integration · Easy
To integrate Retrofit into a Gradle-based Android project, which section of the build.gradle file do you add its dependency to?
Not quite. Try another option.
Answer: dependencies
External library dependencies like Retrofit are added to the dependencies block in the module-level build.gradle file.
Question 5 of 60 · Handling API Requests · Easy
In Retrofit, what does the @GET annotation signify?
Not quite. Try another option.
Answer: It specifies that the request is an HTTP GET request.
The @GET annotation is used on a method in your API interface to declare that it will perform an HTTP GET request, which is typically used for fetching data from a server.
Question 6 of 60 · Handling API Requests · Easy
How are API endpoints defined in Retrofit?
Not quite. Try another option.
Answer: Inside a Java or Kotlin interface using annotations
Retrofit turns your API into a Java/Kotlin interface. You define endpoints as methods within this interface, using annotations like @GET, @POST, etc. to specify the HTTP method and URL.
Question 7 of 60 · Handling API Requests · Easy
What is the purpose of the @Path annotation in a Retrofit interface method?
Not quite. Try another option.
Answer: To replace a placeholder in the URL path with a dynamic value
The @Path annotation binds the value of a method parameter to a named placeholder in the URL path. For example, in /users/{id}, @Path("id") would replace {id}.
Question 8 of 60 · Handling API Requests · Easy
If you want to add a URL parameter like ?sort=new, which Retrofit annotation would you use?
Not quite. Try another option.
Answer: @Query
The @Query annotation adds a parameter to the URL's query string. For example, @Query("sort") sortBy: String with the value "new" would append ?sort=new to the URL.
Question 9 of 60 · Parsing and Displaying Data · Easy
Which of the following is a popular JSON parsing library often used with Retrofit as a converter?
Not quite. Try another option.
Answer: Gson
Gson is a library from Google used to convert Java/Kotlin Objects into their JSON representation and vice versa. It's frequently integrated with Retrofit via GsonConverterFactory.
Question 10 of 60 · Parsing and Displaying Data · Easy
In the context of using Retrofit with a JSON API, what is the role of a data class (or POJO)?
Not quite. Try another option.
Answer: To model the structure of the expected JSON response
A data class (in Kotlin) or a POJO (Plain Old Java Object) defines the fields that match the keys in the JSON data. A converter like Gson uses this model to automatically parse the JSON into an object.
Question 11 of 60 · Parsing and Displaying Data · Easy
What is the purpose of GsonConverterFactory.create() when building a Retrofit instance?
Not quite. Try another option.
Answer: To tell Retrofit to use Gson for JSON serialization and deserialization
Calling .addConverterFactory(GsonConverterFactory.create()) on the Retrofit builder registers Gson as the converter that will handle converting JSON responses into objects and vice versa.
Question 12 of 60 · Parsing and Displaying Data · Easy
Which Android UI component is most commonly used to display a list of items fetched from an API?
Not quite. Try another option.
Answer: RecyclerView
RecyclerView is a highly efficient and flexible component designed for displaying large, scrollable lists of data, making it ideal for showing data fetched from an API.
Question 13 of 60 · Parsing and Displaying Data · Easy
To automatically parse a JSON object into a Kotlin data class, the variable names in the data class should typically match what?
Not quite. Try another option.
Answer: The keys in the JSON object
By default, converters like Gson map the keys from the JSON object to the properties in your data class that have the exact same name.
Question 14 of 60 · Asynchronous Networking · Easy
Which method on a Retrofit Call object is used to execute a network request asynchronously?
Not quite. Try another option.
Answer: enqueue()
The enqueue() method asynchronously sends the request and notifies your app with a callback when a response is ready, without blocking the main thread. execute() runs the request synchronously.
Question 15 of 60 · Asynchronous Networking · Easy
What is the main reason for making network requests asynchronously in an Android app?
Not quite. Try another option.
Answer: It prevents the UI thread from blocking, avoiding an 'Application Not Responding' (ANR) error.
Long-running operations like network calls must be done off the main (UI) thread. Asynchronous execution keeps the UI responsive to user input, preventing ANR errors.
Question 16 of 60 · Asynchronous Networking · Easy
When using Kotlin Coroutines with Retrofit, what keyword is added to an interface method to make it a non-blocking function?
Not quite. Try another option.
Answer: suspend
The suspend keyword marks a function as one that can be paused and resumed later. Retrofit uses this to perform the network request on a background thread without blocking the calling coroutine.
Question 17 of 60 · Authentication · Easy
What is the most common and scalable way to add a dynamic authentication token to every request made with Retrofit?
Not quite. Try another option.
Answer: Use an OkHttp Interceptor to add an Authorization header
An OkHttp Interceptor is the ideal solution. It can intercept every outgoing request, allowing you to dynamically add a header (like Authorization) before the request is sent to the server.
Question 18 of 60 · Authentication · Easy
Which HTTP header is conventionally used to send an API token for authentication, often prefixed with "Bearer"?
Not quite. Try another option.
Answer: Authorization
The Authorization header is the standard HTTP header for sending credentials. For token-based authentication, the value is typically formatted as Bearer {your_token}.
Question 19 of 60 · Authentication · Easy
In a Retrofit API interface, the @Header annotation is used for what purpose?
Not quite. Try another option.
Answer: To add a static HTTP header to a specific request
The @Header annotation lets you add a custom HTTP header to a single API call by passing it as a method parameter. For adding a header to all requests, an Interceptor is preferred.
Question 20 of 60 · Handling API Requests · Easy
Which annotation is used to send a complete object as the request body, typically for an HTTP POST or PUT request?
Not quite. Try another option.
Answer: @Body
The @Body annotation is used on a method parameter to specify that its value (usually a data class instance) should be serialized and used as the HTTP request body.
Question 21 of 60 · Retrofit Basics and Integration · Medium
When configuring a Retrofit.Builder, you add multiple Converter.Factory instances, first GsonConverterFactory and then MoshiConverterFactory. Which converter will Retrofit attempt to use first for response parsing?
Not quite. Try another option.
Answer: The one added first (GsonConverterFactory).
Retrofit iterates through the list of converters in the order they were added. It uses the first one that can handle the given type. Therefore, the order of adding converters is significant.
Question 22 of 60 · Retrofit Basics and Integration · Medium
You are setting up a Retrofit instance. Consider the following code:
kotlin
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
What essential component is missing for this instance to make a successful network request to https://api.example.com/users?
Not quite. Try another option.
Answer: A baseUrl().
A base URL is mandatory for Retrofit to resolve the relative paths defined in the API interface. Without it, Retrofit will throw an IllegalStateException when you try to create the service.
Question 23 of 60 · Retrofit Basics and Integration · Medium
In the context of Retrofit, what is the primary role of defining an interface with annotations like @GET and @POST?
Not quite. Try another option.
Answer: To serve as a declarative specification of the API endpoints, which Retrofit uses to generate the actual network request code at runtime.
The annotated interface acts as a blueprint. Retrofit uses Java's dynamic proxy feature to create a concrete implementation of this interface that handles making the HTTP requests based on the annotations.
Question 24 of 60 · Retrofit Basics and Integration · Medium
Why would a developer explicitly provide a custom OkHttpClient to the Retrofit.Builder using .client(myOkHttpClient)?
Not quite. Try another option.
Answer: To configure advanced features like setting timeouts, adding interceptors for logging or authentication, and managing caching.
While Retrofit creates a default OkHttpClient, providing a custom one allows for fine-grained control over the networking layer, which is essential for production apps to handle things like logging, authentication headers, and connection timeouts.
Question 25 of 60 · Handling API Requests · Medium
Given the Retrofit interface method:
kotlin
@GET("group/{id}/users")
fun groupList(@Path("id") groupId: Int, @Query("sort") sort: String): Call<List<User>>
If you call this method with groupList(42, "desc"), what will be the resulting relative URL?
Not quite. Try another option.
Answer: group/42/users?sort=desc
The @Path("id") annotation replaces the {id} placeholder in the URL with the value 42. The @Query("sort") annotation appends ?sort=desc as a query parameter to the URL.
Question 26 of 60 · Handling API Requests · Medium
When sending data in the body of a POST request, what is the key difference between using the @Body and @Field annotations in a Retrofit interface?
Not quite. Try another option.
Answer: @Body sends a single object serialized as the request body (e.g., as JSON), while @Field is used for sending individual form-urlencoded key-value pairs.
You use @Body to pass a complete object that a converter (like Gson) will serialize into the request body. In contrast, @Field is used with the @FormUrlEncoded annotation to send data as if it were from an HTML form.
Question 27 of 60 · Handling API Requests · Medium
Your app needs to send a unique, dynamically generated X-Request-ID header with each API call. Which Retrofit annotation is the most appropriate for this purpose when the ID changes for every call?
Not quite. Try another option.
Answer: @Header as a method parameter.
@Header("X-Request-ID") requestId: String allows you to pass the value for the header dynamically when you invoke the method. @Headers is for static headers, and @HeaderMap is for when you have multiple dynamic headers to pass in a Map.
Question 28 of 60 · Handling API Requests · Medium
You need to make a POST request to an endpoint that expects data in application/x-www-form-urlencoded format. Which combination of annotations is required on your Retrofit interface method?
Not quite. Try another option.
Answer: @POST, @FormUrlEncoded, and one or more @Field annotations.
The @FormUrlEncoded annotation specifies the request's MIME type. The @Field("key") annotation then provides the individual key-value pairs that will be form-encoded into the request body.
Question 29 of 60 · Handling API Requests · Medium
If you use the @Url annotation in a Retrofit interface method parameter, what is a key requirement for the endpoint definition in the annotation (e.g., @GET)?
Not quite. Try another option.
Answer: The @GET annotation's value must be empty.
When using @Url, the parameter provides the full URL for the request, completely overriding the base URL and any relative path in the @GET, @POST, etc., annotation. Therefore, the path in the method annotation (e.g., @GET("")) must be empty.
Question 30 of 60 · Parsing and Displaying Data · Medium
You are using GsonConverterFactory and your API returns a JSON object. If a field exists in the JSON response but is not defined in your corresponding Kotlin data class, what is the default behavior of Gson?
Not quite. Try another option.
Answer: The field will be ignored, and parsing will continue successfully for the other fields.
By default, Gson is lenient and will simply ignore any fields in the JSON that do not have a corresponding property in the target Java/Kotlin object. This makes APIs more robust to changes.
Question 31 of 60 · Parsing and Displaying Data · Medium
The API returns a JSON with a field named "first_name". Your Kotlin data class has a property named firstName. How can you correctly map this field using Gson without changing the property name in your data class?
Not quite. Try another option.
Answer: Use the @SerializedName("first_name") annotation on the firstName property.
The @SerializedName annotation is provided by the Gson library specifically for this purpose. It tells Gson to map the JSON key specified in the annotation to the class property it annotates.
Question 32 of 60 · Parsing and Displaying Data · Medium
An API endpoint /users returns a JSON array of user objects, like [ { "id": 1, "name": "Alice" }, { "id": 2, "name": "Bob" } ]. What should be the return type of the corresponding method in your Retrofit interface?
Not quite. Try another option.
Answer: Call<List<User>>
To map a JSON array to a collection of objects, you should use a parameterized type like List<T> or Array<T> (which can be represented as User[] in Java). Call<List<User>> is the most common and idiomatic way to handle a list of objects in Kotlin/Java.
Question 33 of 60 · Parsing and Displaying Data · Medium
What is the most appropriate use case for creating a custom Gson TypeAdapter and registering it with your Retrofit instance?
Not quite. Try another option.
Answer: When you need to parse a JSON field that can be either a single object or an array of objects into a consistent list format.
A TypeAdapter gives you complete control over serialization and deserialization. It's perfect for handling non-standard or inconsistent JSON structures, such as a field that is sometimes an object and sometimes an array, which would otherwise cause a parsing error.
Question 34 of 60 · Asynchronous Networking · Medium
In Retrofit, which statement correctly compares call.execute() and call.enqueue()?
Not quite. Try another option.
Answer: execute() is synchronous and blocks the current thread, so it must be called from a background thread. enqueue() is asynchronous and safely executes the request on a background thread, delivering results to the main thread via callbacks.
Calling a blocking network operation like execute() on the Android main thread will cause a NetworkOnMainThreadException. enqueue() is designed for Android's event-driven model, performing work in the background and posting results back on the main thread.
Question 35 of 60 · Asynchronous Networking · Medium
What is the primary advantage of defining a Retrofit service method as a suspend fun for use with Kotlin Coroutines, compared to the traditional Call<T> with enqueue()?
Not quite. Try another option.
Answer: It allows writing asynchronous code in a sequential, non-blocking manner, which simplifies error handling and avoids "callback hell".
suspend functions allow you to write asynchronous operations as if they were synchronous. You can use standard try-catch blocks for error handling and the code is generally more readable and maintainable than nested callbacks.
Question 36 of 60 · Asynchronous Networking · Medium
When using call.enqueue(callback), if the server responds with an HTTP status code of 404 (Not Found), which part of the Callback will be executed?
Not quite. Try another option.
Answer: The onResponse() method, where response.isSuccessful() will be false.
The onFailure() callback is reserved for network errors (e.g., no internet connection). An HTTP error code like 404 is a valid response from the server, so onResponse() is called. You must then check response.isSuccessful() (which checks for codes in the 200-299 range) to determine if the call succeeded.
Question 37 of 60 · Asynchronous Networking · Medium
When using a suspend function in a Retrofit interface, how should you handle potential network errors like a timeout or no internet connectivity?
Not quite. Try another option.
Answer: By wrapping the suspend function call in a try-catch block and catching IOException or other relevant exceptions.
Retrofit's coroutine adapter throws exceptions for failures. Network-level issues (like timeouts) typically throw an IOException, while HTTP error codes (like 4xx or 5xx) throw an HttpException. These must be caught using a standard try-catch block.
Question 38 of 60 · Authentication · Medium
What is the most common and maintainable way to add an Authorization: Bearer <token> header to every request made through a single Retrofit instance?
Not quite. Try another option.
Answer: Creating an OkHttp Interceptor that adds the header to each outgoing request.
An OkHttp Interceptor is the ideal solution. It intercepts every request before it's sent, allowing you to modify it (e.g., by adding a header). This is centralized, reusable, and separates authentication logic from the API interface definitions.
Question 39 of 60 · Authentication · Medium
Your application uses an OAuth 2.0 access token that expires. When a request fails with a 401 Unauthorized error, you need to use a refresh token to get a new access token and then retry the original request. Which OkHttp component is best suited for implementing this logic?
Not quite. Try another option.
Answer: An Authenticator.
OkHttp's Authenticator is specifically designed for this purpose. It is invoked automatically when the server responds with a 401 or 407 status code, giving you a chance to refresh the token and return a new request with the updated credentials, which OkHttp will then retry.
Question 40 of 60 · Authentication · Medium
You need to add a static API key as a query parameter (e.g., ?api_key=YOUR_KEY) to all requests made by Retrofit. Which is the most efficient and cleanest approach?
Not quite. Try another option.
Answer: Use an OkHttp Interceptor to intercept the request, retrieve its URL, and append the new query parameter.
An interceptor provides a single, centralized place to modify all outgoing requests. You can get the original request's URL, use HttpUrl.Builder to add the api_key query parameter, and then build a new request to proceed with. This avoids cluttering every method in your API interface with the same parameter.
Question 41 of 60 · Retrofit Basics and Integration · Hard
You have configured a Retrofit instance with two custom Converter.Factory implementations, FactoryA and FactoryB, added in that order: retrofitBuilder.addConverterFactory(FactoryA).addConverterFactory(FactoryB). FactoryA can handle TypeX but returns null from its responseBodyConverter method for TypeY. FactoryB can handle TypeY. If you make an API call defined as fun getData(): Call<TypeY>, what will be the outcome?
Not quite. Try another option.
Answer: Retrofit will skip FactoryA since it returned null for TypeY and will successfully use FactoryB to convert the response.
Retrofit iterates through its list of converter factories in the order they were added. For a given type, it calls the factory's responseBodyConverter method. If a factory returns null, it signifies that it cannot handle that specific type, and Retrofit proceeds to the next factory in the list. The call only fails if no registered factory can handle the type.
Question 42 of 60 · Authentication · Hard
In a multithreaded application, multiple concurrent API calls fail with a 401 Unauthorized error, triggering your custom Retrofit Authenticator. A naive implementation of the authenticate() method immediately calls the token refresh endpoint. What is the primary race condition this approach creates, and what is the correct way to solve it?
Not quite. Try another option.
Answer: The race condition is making multiple, redundant token refresh requests; solve by using a synchronized block to ensure only one thread refreshes the token while others wait for the result.
When multiple threads fail authentication simultaneously, they all enter the authenticate method. Without synchronization, each will independently trigger a token refresh request, which is inefficient and can lead to server-side issues. The standard solution is to use a synchronized block. The first thread entering performs the refresh, while subsequent threads wait. Once the token is refreshed, waiting threads can retry their original request with the new token.
Question 43 of 60 · Asynchronous Networking · Hard
Consider the following Kotlin Coroutines code within a ViewModel: viewModelScope.launch { val userDeferred = async { api.getUser() }; val postsDeferred = async { api.getPosts() }; try { val user = userDeferred.await(); val posts = postsDeferred.await(); } catch (e: Exception) { // handle error } }. If the api.getPosts() call fails with an IOException but api.getUser() completes successfully before the failure, what is the state of the viewModelScope's Job and what happens to the result of api.getUser()?
Not quite. Try another option.
Answer: The parent Job is cancelled, and the result of getUser() is lost as the try-catch block catches the exception from the failing await().
This scenario demonstrates structured concurrency and exception propagation in coroutines. When multiple async builders are used within a coroutine scope, a failure in any one of them will cause the parent job (and thus all other child jobs in that scope) to be cancelled immediately. When postsDeferred.await() throws the exception, the parent Job is cancelled. Even if userDeferred had completed, its result is effectively discarded because the coroutine is cancelled before the result can be used, and the exception propagates up.
Question 44 of 60 · Handling API Requests · Hard
You need to implement a file upload using a @Multipart request. The API requires a JSON object and a file to be sent in the same request. How should you define the RequestBody for the JSON part to ensure it is correctly formatted with Content-Type: application/json?
Not quite. Try another option.
Answer: Use a generic RequestBody: @Part("data") data: RequestBody where the body is created with RequestBody.create("application/json; charset=utf-8".toMediaType(), jsonString)
While Retrofit's converters can automatically convert objects to RequestBody for @Body, this mechanism does not apply to @Part in the same way for complex types like JSON. To explicitly set the Content-Type for a multipart part, you must manually create a RequestBody using RequestBody.create(), specifying the correct MediaType (application/json) and the raw JSON string as the content.
Question 45 of 60 · Parsing and Displaying Data · Hard
An API endpoint returns a JSON array of 'events'. Each event object has a "type" field ("message" or "image") and other fields that differ based on the type. How would you model this polymorphic data using Moshi and a custom JsonAdapter.Factory for seamless parsing into a sealed class Event?
Not quite. Try another option.
Answer: Use @JsonClass(generator = "sealed:type") on the sealed class and @Json(name = ...) on the subclasses to automatically delegate parsing based on the "type" field.
Moshi provides excellent support for polymorphism with sealed classes. By annotating the sealed parent class with @JsonClass(generator = "sealed:<label_key>") (where <label_key> is the field name, e.g., "type"), you instruct Moshi to use this field to determine which subclass to deserialize into. Each subclass can then be annotated with @Json(name = "<label_value>") to map it to a specific value of the type field.
Question 46 of 60 · Authentication · Hard
You have implemented a Retrofit Authenticator to refresh a JWT. The token refresh endpoint itself is protected and requires the expired token to be passed for validation. What critical step must you take when creating the OkHttpClient for the refresh API call inside the authenticate() method to avoid an infinite loop?
Not quite. Try another option.
Answer: Both B and C are valid strategies, but using a separate OkHttpClient is the cleaner, recommended approach.
If the token refresh call itself fails with a 401 error, and it uses the same OkHttpClient, it will re-trigger the same Authenticator, leading to an infinite recursive loop. To break this cycle, you must ensure the refresh call does not trigger the authenticator. The cleanest way is to use a dedicated OkHttpClient instance for the refresh service that omits the Authenticator. Alternatively, you could add a distinguishing header to the refresh request and add logic to your Authenticator to ignore 401s for requests with that header.
Question 47 of 60 · Retrofit Basics and Integration · Hard
A Retrofit service method is defined with a dynamic URL: suspend fun getFile(@Url fileUrl: String): ResponseBody. The base URL of the Retrofit instance is https://api.example.com/v1/. If you call this method with getFile("images/logo.png"), what will be the final request URL, and why?
Not quite. Try another option.
Answer: The call will fail with an IllegalArgumentException because a full, absolute URL is required for @Url.
The @Url annotation is designed to completely replace the base URL configured on the Retrofit instance. As such, it requires a fully-qualified URL including the scheme (e.g., https://). If a relative path is provided, Retrofit cannot resolve it and will throw an IllegalArgumentException at runtime, stating that the URL must have a scheme.
Question 48 of 60 · Asynchronous Networking · Hard
When defining a Retrofit service interface with suspend functions, what is the fundamental difference in error handling between a function returning Response<T> versus one returning just T when the server responds with an HTTP error code like 404 or 500?
Not quite. Try another option.
Answer: Returning T throws an HttpException which must be caught, while Response<T> returns a response object with isSuccessful = false and does not throw.
When a suspend function returns the direct body type T, Retrofit's suspend adapter will check if the response was successful (in the 2xx range). If not, it throws an HttpException. This forces you to use try-catch for server-side errors. Conversely, returning Response<T> wraps the result. The call itself succeeds from the perspective of the coroutine (no exception is thrown for HTTP error codes), and you receive a Response object where you must manually check response.isSuccessful() and handle the success or error case by parsing response.body() or response.errorBody().
Question 49 of 60 · Handling API Requests · Hard
An API requires you to send a DELETE request with a JSON body. Which combination of Retrofit annotations would you use to define this service method?
By default, Retrofit's @DELETE annotation does not permit a request body, as it's unconventional for the DELETE HTTP method. Attempting to add a @Body will result in a compile-time error. To override this behavior for APIs that require it, you must use the more generic @HTTP annotation, explicitly specifying the method, path, and setting the hasBody parameter to true.
Question 50 of 60 · Parsing and Displaying Data · Hard
An API for a specific field sometimes returns a JSON object {"key":"value"} and other times returns an empty JSON array [] to signify 'no data'. A standard Gson/Moshi parser would crash with a type mismatch. What is the most robust way to handle this using a custom adapter?
Not quite. Try another option.
Answer: Write a custom JsonAdapter that, in its fromJson method, checks the next token. If it's BEGIN_ARRAY, it consumes the array and returns a null or default object. If it's BEGIN_OBJECT, it proceeds with normal object parsing.
This is a classic data inconsistency problem best solved at the parsing layer. A custom JsonAdapter (for Moshi) or TypeAdapter (for Gson) gives you direct control over the parsing stream. By peeking at the next JSON token (JsonReader.peek()), you can detect whether the incoming value is an array or an object and handle each case gracefully within a single parsing logic, mapping the inconsistent API behavior to a consistent data model.
Question 51 of 60 · Retrofit Basics and Integration · Hard
What is the primary purpose of a Retrofit CallAdapter.Factory, and in which scenario is creating a custom one absolutely necessary?
Not quite. Try another option.
Answer: To adapt the standard Call<T> object into another type, such as Single<T> for RxJava or a custom Result<T> wrapper. It's necessary when not using Call or coroutine suspend functions.
A Converter.Factory handles data format conversion. A CallAdapter.Factory, on the other hand, determines the return type of your service methods. Retrofit's default adapter supports Call<T>. The kotlinx-coroutines-adapter adds support for suspend functions. If you want your service methods to return a different container type, like an RxJava observable (Single, Observable) or a custom sealed class for handling success/failure (e.g., ApiResponse<T>), you must provide a CallAdapter.Factory that knows how to create and handle that specific type.
Question 52 of 60 · Authentication · Hard
If your Authenticator's authenticate() method returns null, what is the direct consequence for the original request that received the 401 and for any other requests that were queued by OkHttp while the authenticator was running?
Not quite. Try another option.
Answer: The original request and all queued requests are immediately cancelled, and the call chain is terminated for all of them.
Returning null from the authenticate method is the signal to OkHttp/Retrofit that authentication has failed and cannot be recovered (e.g., the refresh token is invalid). This action causes the original request to fail permanently. Furthermore, OkHttp will not attempt any other requests that were enqueued and waiting for authentication, and it will fail all of them immediately. It is the definitive 'give up' signal.
Question 53 of 60 · Handling API Requests · Hard
Consider a Retrofit method: fun search(@Query("q") query: String?, @Query("sort") sort: String = "asc"). How does Retrofit handle a null value passed for the query parameter, and how does it handle the default value for the sort parameter if it's not provided by the caller?
Not quite. Try another option.
Answer: The parameter q will be omitted from the URL if its value is null. The sort parameter will be included with the value "asc" if not specified.
Retrofit is designed to handle nullable query parameters gracefully. If the value passed to a @Query annotated parameter is null, Retrofit simply omits that parameter and its key from the generated URL. Kotlin's default parameter values work as expected; if the caller does not provide a value for sort, the compiler will pass the default value "asc", which Retrofit will then include in the URL as sort=asc.
Question 54 of 60 · Parsing and Displaying Data · Hard
When using the Gson converter, you have a data class with a lateinit var property. The corresponding field is missing from the JSON response. What will be the outcome during deserialization?
Not quite. Try another option.
Answer: Gson will skip the field, and the property will remain uninitialized, causing an UninitializedPropertyAccessException only when it's accessed.
Gson's default behavior is to skip fields in a data class that are not present in the JSON payload. For a lateinit var, this means the property is never assigned a value during deserialization. The creation of the object itself succeeds, but the property remains in an uninitialized state. The application will only crash with an UninitializedPropertyAccessException at the point where your code first attempts to read or write to that specific property.
Question 55 of 60 · Asynchronous Networking · Hard
You are using Flow with Retrofit to implement a real-time search feature. A code snippet in your ViewModel is: searchQuery.debounce(300).flatMapLatest { query -> flow { emit(api.search(query)) } }.catch { ... }. If a user types quickly, causing a new query to be emitted while a previous api.search() call is still in flight, what does flatMapLatest ensure?
Not quite. Try another option.
Answer: It cancels the ongoing network request from the previous query and starts a new one for the latest query.
The flatMapLatest operator is key to building responsive UIs that depend on the latest data. When a new value is emitted by the upstream flow (searchQuery), flatMapLatest cancels the coroutine that was executing the block for the previous value. Because Retrofit's suspend functions are cancellable, this action effectively cancels the in-flight network request, preventing outdated results from being processed and ensuring system resources are used efficiently for the most recent user input.
Question 56 of 60 · Retrofit Basics and Integration · Hard
If you add a HttpLoggingInterceptor as a network interceptor (addNetworkInterceptor) versus an application interceptor (addInterceptor), how does the logged Request object differ when a request is redirected by the server (e.g., a 301 response)?
Not quite. Try another option.
Answer: The application interceptor logs only the initial request to the original URL. The network interceptor will be invoked multiple times, logging the request to the original URL and then the subsequent request to the redirected URL.
Application interceptors operate on the high-level, logical request and see it only once, before any network-level concerns like redirects or retries. Network interceptors operate closer to the wire. They see the request as it's about to be sent over the network. In a redirect scenario, the network interceptor will fire for the initial request, see the 301 response, and then fire again for the new request that OkHttp automatically creates to follow the redirect.
Question 57 of 60 · Handling API Requests · Hard
What is the key difference between using @QueryMap with a Map<String, String> and using multiple @Query annotations in a Retrofit service method?
Not quite. Try another option.
Answer: @QueryMap allows for a dynamic number of query parameters to be added at runtime, whereas @Query is for a fixed, known set of parameters defined in the method signature.
The primary purpose of @QueryMap is to provide flexibility. When you have a variable number of query parameters (e.g., for applying user-selected filters), you can construct a Map with these filters at runtime and pass it to @QueryMap. This avoids having to define a method with a potentially huge number of nullable @Query parameters. @Query is used when the parameters are fixed and known at compile time.
Question 58 of 60 · Authentication · Hard
When securing API keys used by your Retrofit/OkHttp client in an Android app, which method provides the strongest protection against static analysis and reverse engineering of the APK?
Not quite. Try another option.
Answer: Storing the key in a native C/C++ library using the NDK and retrieving it via JNI calls.
While no client-side storage is 100% secure, storing secrets in native code (NDK) offers significantly higher protection than other methods. Java/Kotlin bytecode (even when obfuscated) is easier to decompile and analyze than compiled native machine code. BuildConfig fields and XML resources are trivial to extract from an APK. Storing the key in a .so native library and loading it via JNI makes it much harder for attackers to find the key through static analysis.
Question 59 of 60 · Asynchronous Networking · Hard
You make a suspend Retrofit call inside a coroutine launched with supervisorScope. If the network call fails with an IOException, how does this exception affect the supervisorScope and its other child coroutines?
Not quite. Try another option.
Answer: The exception is contained within the failing child coroutine, which is cancelled, but the supervisorScope and its other children continue to run unaffected.
This question tests the core principle of supervisorScope (or SupervisorJob). Unlike a regular coroutineScope, a supervisorScope's cancellation policy is that a failure in one child does not affect the scope itself or any of its other children. The exception is confined to the specific child coroutine where it occurred. This is useful for UI-related tasks where you want independent operations to proceed even if one fails.
Question 60 of 60 · Retrofit Basics and Integration · Hard
When building an OkHttpClient, you can set timeouts using connectTimeout, readTimeout, and callTimeout. If you set a callTimeout of 30 seconds and a readTimeout of 15 seconds, and a server takes 20 seconds to send a response, what will happen?
Not quite. Try another option.
Answer: The request will fail with a SocketTimeoutException because the readTimeout of 15 seconds was exceeded.
callTimeout is the total timeout for the entire call, from the moment the request is initiated to the moment the response is fully read. readTimeout is a more specific timer that applies to the time between receiving consecutive data packets from the server. If the server connects but then takes longer than the readTimeout to start sending the response body, OkHttp will throw a SocketTimeoutException, even if the total time is still within the callTimeout. The most restrictive, relevant timeout is the one that triggers the failure.
That's unit 3
Answer a few questions and your score shows up here.
Nearly through. Did unit 3 of CSE227 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 3 of CSE227 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill;
the rest comes out of a student's own pocket: the domain, the storage, and keeping
the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason.
to try again.