-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Check accuracy before updating user's location #102
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThis pull request introduces modifications across several files, focusing on updating configuration settings and enhancing location management functionalities. The Changes
Possibly related PRs
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 9
🧹 Outside diff range and nitpick comments (7)
data/src/main/java/com/canopas/yourspace/data/storage/LocationCache.kt (2)
23-25
: LGTM: New method to store last extracted location.The
putLastExtractedLocation
method is implemented correctly. It follows the class's naming conventions and properly stores the location in the cache.Consider adding input validation to ensure that neither
location
noruserId
is null before storing in the cache.
Line range hint
40-43
: Update theclear
method to include the new cache.The
clear
method currently doesn't clear the newly addedlastExtractedLocation
cache. This could lead to stale location data persisting when other caches are cleared.Update the
clear
method to include the new cache:fun clear() { lastJourneyCache.evictAll() lastFiveLocationsCache.evictAll() + lastExtractedLocation.evictAll() }
data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (1)
38-39
: Approve changes with a suggestion for error handlingThe modifications to the
saveCurrentJourney
method are well-implemented:
- Returning
String
instead of using a callback simplifies usage and allows for better error propagation.- Removal of the
newJourneyId
parameter aligns with the new return type.- Moving
updateAt
to the end of the parameter list maintains backwards compatibility and follows Kotlin conventions.These changes improve the method's usability and adhere to Kotlin best practices.
Consider adding error handling to catch potential exceptions from the Firestore operation:
suspend fun saveCurrentJourney( // ... other parameters ... updateAt: Long? = null ): String { val docRef = journeyRef(userId).document() val journey = LocationJourney( // ... journey initialization ... ) return try { docRef.set(journey).await() docRef.id } catch (e: Exception) { Timber.e(e, "Error saving current journey") throw e // or handle the error as appropriate for your use case } }This addition would provide better visibility into potential issues during the save operation.
Also applies to: 57-58
data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (4)
60-61
: Adjust logging level from error to debug or infoThe log message
"Skipping location update due to low accuracy: $accuracy"
indicates a normal control flow and not an error condition. UsingTimber.e
(error) might be misleading. Consider usingTimber.d
(debug) orTimber.i
(info) to reflect that this is expected behavior.
67-68
: Adjust logging level from error to debug or infoThe message
"Distance is less than $MINIMUM_DISTANCE meters, skipping location update"
represents normal operation when the user hasn't moved significantly. Logging this as an error withTimber.e
may not be appropriate. Consider switching toTimber.d
orTimber.i
to indicate that this is standard behavior.
Line range hint
77-79
: Catch more specific exceptions instead of generic ExceptionCatching the generic
Exception
can mask other unexpected runtime exceptions and make debugging harder. Consider catching more specific exceptions that are likely to be thrown during the location saving process, such asIOException
or any custom exceptions.
56-56
: Consider logging when location has no accuracyCurrently, when
extractedLocation.hasAccuracy()
returnsfalse
, the loop continues without any logging. For better debugging and monitoring, consider adding a log statement to indicate that a location update was skipped due to missing accuracy information.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (7)
- .idea/compiler.xml (1 hunks)
- .idea/misc.xml (1 hunks)
- data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (4 hunks)
- data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (9 hunks)
- data/src/main/java/com/canopas/yourspace/data/service/location/ApiJourneyService.kt (2 hunks)
- data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt (4 hunks)
- data/src/main/java/com/canopas/yourspace/data/storage/LocationCache.kt (2 hunks)
✅ Files skipped from review due to trivial changes (1)
- .idea/compiler.xml
🧰 Additional context used
🔇 Additional comments (14)
.idea/misc.xml (2)
4-4
: Java version downgraded from 21 to 17The project's Java version has been changed from 21 to 17. This is a significant change that will affect the entire project's compilation and potentially its runtime behavior.
To ensure this change is applied consistently and to understand its impact, please run the following checks:
#!/bin/bash # Check for Java 21 specific features that might need to be refactored rg --type java "sealed|record\s+class|pattern\s+matching.*instanceof" # Verify build files are updated accordingly rg --type gradle "sourceCompatibility|targetCompatibility" # Check if any dependencies require Java 21 rg --type gradle "requires\s+java\s*21"Please ensure that:
- All team members are aware of this change and have updated their local environments.
- CI/CD pipelines are updated to use Java 17.
- Any code using Java 21 specific features has been refactored.
- All dependencies are compatible with Java 17.
Consider documenting the reason for this downgrade in the project's README or a similar location to provide context for future developers.
3-3
: New external storage configuration addedThe addition of
<component name="ExternalStorageConfigurationManager" enabled="true" />
indicates that the project is now using external storage for some of its configuration. This change doesn't directly affect the code but may impact how the project is managed in the IDE.To ensure this change is consistent with other project files, let's check for any related configurations:
✅ Verification successful
External storage configuration addition verified
The addition of
<component name="ExternalStorageConfigurationManager" enabled="true" />
has been verified, and no additional references to this component were found in the project. This change does not affect the code directly but may impact how the project is managed within the IDE.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for other files that might reference external storage configuration rg --type xml "ExternalStorageConfigurationManager"Length of output: 472
Script:
#!/bin/bash # Search for references to ExternalStorageConfigurationManager in all XML files rg "ExternalStorageConfigurationManager" --glob "*.xml"Length of output: 55
data/src/main/java/com/canopas/yourspace/data/storage/LocationCache.kt (2)
12-12
: LGTM: New cache for last extracted location.The addition of
lastExtractedLocation
cache is well-implemented. It usesLruCache
appropriately, has a reasonable size, and maintains proper encapsulation.
27-29
: LGTM: New method to retrieve last extracted location.The
getLastExtractedLocation
method is well-implemented. It follows the class's naming conventions, handles potential null values correctly, and has an appropriate nullable return type.data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (1)
64-64
: Confirm behavior when lastLocation is nullWhen
lastLocation
isnull
,distance
is set toFloat.MAX_VALUE
, which ensures thatupdateLocation()
is called. Verify that this is the intended behavior and that updating the location when there is no previous location is desired.data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (8)
11-11
: Approved: Added import forLocationManager
The import statement correctly brings in the
LocationManager
class needed for the new functionality.
25-26
: Verify Dependency Injection forLocationManager
You've added
locationManager
as a new dependency in the constructor. Please ensure that:
- All instances of
JourneyRepository
are provided with aLocationManager
instance.- The Dependency Injection framework (e.g., Dagger/Hilt) is properly configured to inject
LocationManager
.
80-86
: Verify Removal ofcreatedAt
andupdatedAt
ParametersYou've removed
createdAt
andupdatedAt
from thesaveCurrentJourney
method call. Ensure that:
- The
saveCurrentJourney
method has default handling for these parameters internally.- Omitting these parameters doesn't lead to incorrect timestamp data or errors when saving a journey.
110-113
: Approved: Added Day Change Check for Last Known JourneyIncluding the
isDayChanged
check ensures that the journey data remains accurate by handling day transitions properly.
172-176
: Approved: Adjusted Location Requests Based on User MovementThe logic correctly switches the location request strategy:
- When the user starts moving, it switches to time-based requests.
- When the user remains steady, it switches to distance-based requests.
This should optimize battery usage and location accuracy.
199-202
: Approved: Updated Location Requests When User Stops MovingBy transitioning to distance-based updates when the user stops moving, you optimize the application's performance and resource utilization.
229-237
: Verify Null Handling forrouteDuration
and Consistency in Method CallsIn this call to
saveCurrentJourney
:
routeDuration
is explicitly set tonull
.createdAt
andupdatedAt
are omitted.Please verify:
- That
routeDuration
beingnull
is acceptable and won't cause issues when saving the journey.- The
saveCurrentJourney
method can handle these parameters beingnull
or absent.- Consistency in parameter usage across all calls to
saveCurrentJourney
.
358-358
: Verify Parameters forsaveCurrentJourney
MethodIn this call, only
fromLatitude
andfromLongitude
are provided. Ensure that:
- The method can handle calls with only these parameters.
- Any required parameters are either optional or have default values.
- This won't lead to incomplete journey data being saved.
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt (1)
78-80
:⚠️ Potential issueVerify that
request
is always initialized before starting location trackingWhile
request
is initialized in theinit
block, it's crucial to ensure thatstartLocationTracking()
cannot be called before initialization. If there is any possibility ofstartLocationTracking()
being invoked before the constructor completes, consider guarding against uninitialized access.To verify, ensure that no code paths allow
startLocationTracking()
to be called before object initialization completes.
data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt
Outdated
Show resolved
Hide resolved
data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt
Show resolved
Hide resolved
data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt
Show resolved
Hide resolved
@@ -21,18 +22,20 @@ import javax.inject.Inject | |||
import javax.inject.Singleton | |||
|
|||
private const val LOCATION_UPDATE_INTERVAL = 10000L | |||
private const val MINIMUM_DISTANCE = 10f |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider making MINIMUM_DISTANCE
configurable
The MINIMUM_DISTANCE
constant is currently hardcoded to 10f
. Making this value configurable or injecting it via the constructor can enhance the flexibility of the LocationManager
, allowing different parts of the application to specify their desired minimum distance for location updates.
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt
Outdated
Show resolved
Hide resolved
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt
Outdated
Show resolved
Hide resolved
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt
Outdated
Show resolved
Hide resolved
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt
Outdated
Show resolved
Hide resolved
data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (3)
data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (3)
42-44
: LGTM: Improved steady location trackingThe addition of timer cancellation and restarting in
saveLocationJourney
enhances the accuracy of steady location tracking. This ensures that the timer is properly reset with each new location update.Consider adding a brief comment explaining the purpose of the 5-minute timer for better code readability.
65-84
: LGTM: Well-implemented steady location timerThe
startSteadyLocationTimer
method effectively implements the logic for detecting and handling steady locations. The use of coroutines for asynchronous saving and proper timer cancellation are good practices.Consider adding a catch block to handle potential exceptions in the coroutine launch, ensuring that the timer is always cancelled even if an error occurs during the journey saving process.
146-149
: LGTM: Improved day change handling in getLastKnownLocationThe addition of the day change check in
getLastKnownLocation
enhances the accuracy of location tracking across day boundaries. This prevents the use of outdated journey information when a new day has started.Consider extracting the condition
!isDayChanged(extractedLocation, it)
into a well-named variable for improved readability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (1 hunks)
- data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (9 hunks)
- data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt
- data/src/main/java/com/canopas/yourspace/data/service/location/LocationManager.kt
🧰 Additional context used
🔇 Additional comments (5)
data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (5)
12-15
: LGTM: Improved asynchronous handling with CoroutineScope and TimerThe addition of
CoroutineScope
,Timer
, and related imports, along with the newsteadyLocationTimer
property andscope
, enhances the class's ability to manage asynchronous operations and timed tasks. This change allows for more efficient background processing and better control over location-related operations.Also applies to: 18-19, 32-33
86-89
: LGTM: Proper timer cancellationThe
cancelSteadyLocationTimer
method correctly cancels the timer and sets it to null, which is a good practice to prevent memory leaks and ensure the timer is properly cleaned up.
116-122
: LGTM: Simplified journey saving processThe direct assignment of the
saveCurrentJourney
result tonewJourneyId
streamlines the code. The added comment provides helpful context for the parameter changes.Regarding the past comment about inconsistent use of
createdAt
: This change addresses the inconsistency by removingcreatedAt
andupdatedAt
parameters fromsaveCurrentJourney
. This standardization improves code consistency across different calls to this method.
324-329
: LGTM: Consistent use of createdAt in saveJourneyOnJourneyStoppedThe addition of the
createdAt
parameter in the call tosaveCurrentJourney
ensures consistency in journey creation times. This change addresses the previous concern about inconsistent use ofcreatedAt
across different calls tosaveCurrentJourney
.This improvement enhances the accuracy of journey timelines and resolves the inconsistency highlighted in the past review comment.
Line range hint
1-424
: Overall: Significant improvements to JourneyRepositoryThe changes in this file have substantially improved the
JourneyRepository
class. Key enhancements include:
- Better asynchronous handling with CoroutineScope and Timer.
- Improved steady location tracking mechanism.
- More accurate day change handling in location journeys.
- Consistent use of creation times across journey saving methods.
These improvements enhance the reliability and accuracy of location tracking and journey management. The code is now more robust and consistent in its handling of various scenarios.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- app/src/main/java/com/canopas/yourspace/domain/fcm/YourSpaceFcmService.kt (3 hunks)
- data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt (1 hunks)
- data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- data/src/main/java/com/canopas/yourspace/data/receiver/location/LocationUpdateReceiver.kt
- data/src/main/java/com/canopas/yourspace/data/repository/JourneyRepository.kt
🧰 Additional context used
@Inject | ||
lateinit var locationCache: LocationCache |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider using constructor injection for dependencies.
Using constructor injection for locationCache
and journeyRepository
can improve testability and avoid the use of lateinit
variables. This approach promotes immutability and makes the class easier to unit test.
Also applies to: 91-92
scope.launch { | ||
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "") | ||
extractedLocation?.let { | ||
journeyRepository.saveLocationJourney( | ||
extractedLocation, | ||
authService.currentUser?.id ?: "" | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Simplify null checks for authService.currentUser
.
Since authService.currentUser
is already verified to be non-null at the beginning of the function, you can safely access authService.currentUser.id
without the safe-call operator and default value. This simplifies the code and avoids unnecessary null coalescing.
Apply this diff to simplify the code:
- val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "")
+ val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser.id)
And in the saveLocationJourney
call:
- authService.currentUser?.id ?: ""
+ authService.currentUser.id
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
scope.launch { | |
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "") | |
extractedLocation?.let { | |
journeyRepository.saveLocationJourney( | |
extractedLocation, | |
authService.currentUser?.id ?: "" | |
) | |
scope.launch { | |
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser.id) | |
extractedLocation?.let { | |
journeyRepository.saveLocationJourney( | |
extractedLocation, | |
authService.currentUser.id | |
) |
scope.launch { | ||
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser?.id ?: "") | ||
extractedLocation?.let { | ||
journeyRepository.saveLocationJourney( | ||
extractedLocation, | ||
authService.currentUser?.id ?: "" | ||
) | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add error handling within the coroutine.
Consider adding a try-catch block inside the coroutine to handle any potential exceptions from getLastExtractedLocation
or saveLocationJourney
. This ensures that unexpected errors do not crash the application and can be properly logged or managed.
Apply this diff to add error handling:
scope.launch {
+ try {
val extractedLocation = locationCache.getLastExtractedLocation(userId = authService.currentUser.id)
extractedLocation?.let {
journeyRepository.saveLocationJourney(
extractedLocation,
authService.currentUser.id
)
}
+ } catch (e: Exception) {
+ Timber.e(e, "Error updating location journey")
+ }
}
Committable suggestion was skipped due to low confidence.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Chores