Now, generate an user manual from code
- User
Now, generate an user manual from code
- Assistant
User Manual for ApiClient
The
ApiClientclass is a singleton that serves as a central point for managing HTTP connections and requests to a backend REST API. It abstracts the complexity of configuring networking libraries such as Retrofit and OkHttp, while providing mechanisms to track network activity, handle global events (e.g., unauthorized responses), and manage resources efficiently.
Overview
The
ApiClientis designed to:- Provide a type-safe interface for making API calls using Retrofit.
- Track ongoing network activity and notify the UI when calls start or end.
- Handle global events like unauthorized (HTTP 401) responses.
- Properly shut down resources when the application terminates.
This manual explains how to use the
ApiClienteffectively in your application.
Key Features
1. Singleton Design
The
ApiClientuses a singleton pattern to ensure there is only one instance of the client throughout the application lifecycle. This avoids redundant configurations and ensures consistent behavior.2. Network Activity Tracking
The
ApiClientprovides a JavaFX property (callInProgressProperty) that indicates whether any network call is currently active. This is useful for binding UI elements like loading indicators.3. Global Event Handling
You can register handlers to respond to:
- Changes in network activity status (e.g., when a call starts, ends, or fails).
- Unauthorized (HTTP 401) responses, which are handled globally by the
JsonInterceptor.
4. Resource Management
The
shutdown()method ensures proper cleanup of resources, including shutting down the OkHttp client's executor service, evicting connections, and closing the cache.
Usage Guide
1. Initializing the ApiClient
To use the
ApiClient, obtain its singleton instance:ApiClient apiClient = ApiClient.getInstance();2. Creating API Service Interfaces
Use the
getClient()method to access theClientimplementation, which allows you to create Retrofit service interfaces:MyApiService myApiService = apiClient.getClient().create(MyApiService.class);Here,
MyApiServiceis an interface annotated with Retrofit annotations to define API endpoints.3. Tracking Network Activity
Bind the
callInProgressProperty()to UI elements to show/hide loading indicators:BooleanProperty callInProgress = apiClient.callInProgressProperty(); callInProgress.addListener((observable, oldValue, newValue) -> { if (newValue) { // Show loading indicator } else { // Hide loading indicator } });4. Handling Global Events
a. Network Call Status Handlers
Register a handler to be notified when the overall network activity status changes:
apiClient.getClient().addClientCallHandler(callStatus -> { switch (callStatus) { case START: System.out.println("A network call has started."); break; case END: System.out.println("A network call has ended successfully."); break; case FAILED: System.out.println("A network call has failed."); break; } });To remove a handler:
apiClient.getClient().removeClientCallHandler(handler);b. Unauthorized Response Handlers
Register a handler to respond to HTTP 401 Unauthorized responses:
apiClient.getClient().addUnauthorizedHandler(unused -> { System.out.println("Unauthorized response received. Redirecting to login..."); // Implement logic to redirect the user to the login screen or refresh tokens });To remove a handler:
apiClient.getClient().removeUnauthorizedHandler(handler);5. Changing the Base URL
You can change the base URL for API requests dynamically:
apiClient.getClient().setBaseUrl("https://new-api.example.com/");Note: Changing the base URL after the Retrofit instance has been created does not rebuild the Retrofit client. To apply the new URL, you may need to reinitialize the
ApiClient.6. Shutting Down Resources
When the application is terminating, call the
shutdown()method to release resources:apiClient.shutdown();This ensures that all network-related resources are properly cleaned up.
Best Practices
-
Use Singleton Instance: Always use
ApiClient.getInstance()to access the singleton instance. Avoid creating multiple instances manually. -
Handle Unauthorized Responses Globally: Use the
addUnauthorizedHandler()method to implement centralized logic for handling expired sessions or invalid tokens (e.g., redirecting to the login screen). -
Clean Up Resources: Ensure that
shutdown()is called when the application is exiting to prevent resource leaks. -
Bind UI Elements to
callInProgressProperty: Use thecallInProgressProperty()to bind UI elements like progress bars or loading spinners for a responsive user experience. -
Test with Different Base URLs: If your application supports multiple environments (e.g., development, staging, production), use
setBaseUrl()to switch between them during testing.
Example Workflow
Step 1: Initialize the ApiClient
ApiClient apiClient = ApiClient.getInstance();Step 2: Create a Retrofit Service Interface
Define an interface for your API endpoints:
public interface MyApiService { @GET("/users") Call<List<User>> getUsers(); }Create an instance of the service:
MyApiService myApiService = apiClient.getClient().create(MyApiService.class);Step 3: Make API Calls
Make a network request and handle the response:
Call<List<User>> call = myApiService.getUsers(); call.enqueue(new Callback<>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { if (response.isSuccessful()) { List<User> users = response.body(); System.out.println("Users fetched: " + users); } else { System.out.println("Error fetching users: " + response.code()); } } @Override public void onFailure(Call<List<User>> call, Throwable t) { System.out.println("Request failed: " + t.getMessage()); } });Step 4: Handle Unauthorized Responses
Register a handler for HTTP 401 responses:
apiClient.getClient().addUnauthorizedHandler(unused -> { System.out.println("Session expired. Redirecting to login..."); // Redirect to login screen });Step 5: Shut Down Resources
When the application exits, release resources:
apiClient.shutdown();
Troubleshooting
-
Base URL Not Updating: If changing the base URL via
setBaseUrl()does not take effect, ensure that theApiClientinstance is reinitialized or recreate the Retrofit client. -
Handlers Not Triggering: Verify that handlers are registered correctly and that the
JsonInterceptoris properly configured to detect unauthorized responses. -
Resource Leaks: Ensure that
shutdown()is called when the application terminates to release all network-related resources.
Conclusion
The
ApiClientsimplifies the process of making API calls, tracking network activity, and handling global events. By following the guidelines in this manual, you can integrate it seamlessly into your application and ensure a robust and maintainable networking layer.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.