Skip to content
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

Improve TokenBundleRepositoryImpl to check if API is available #1089

Merged
merged 1 commit into from
Mar 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions auth-data-phone/api/current.api
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package com.google.android.horologist.auth.data.phone.common {
package com.google.android.horologist.auth.data.phone.tokenshare {

@com.google.android.horologist.auth.data.phone.ExperimentalHorologistAuthDataPhoneApi public interface TokenBundleRepository<T> {
method public suspend Object? isAvailable(kotlin.coroutines.Continuation<? super java.lang.Boolean>);
method public suspend Object? update(T? tokenBundle, kotlin.coroutines.Continuation<? super kotlin.Unit>);
}

Expand All @@ -24,13 +25,13 @@ package com.google.android.horologist.auth.data.phone.tokenshare {
package com.google.android.horologist.auth.data.phone.tokenshare.impl {

@com.google.android.horologist.auth.data.phone.ExperimentalHorologistAuthDataPhoneApi public final class TokenBundleRepositoryImpl<T> implements com.google.android.horologist.auth.data.phone.tokenshare.TokenBundleRepository<T> {
ctor public TokenBundleRepositoryImpl(androidx.datastore.core.DataStore<T> dataStore);
ctor public TokenBundleRepositoryImpl(com.google.android.horologist.data.WearDataLayerRegistry registry, optional String key, kotlinx.coroutines.CoroutineScope coroutineScope, androidx.datastore.core.Serializer<T> serializer);
method public suspend Object? isAvailable(kotlin.coroutines.Continuation<? super java.lang.Boolean>);
method public suspend Object? update(T? tokenBundle, kotlin.coroutines.Continuation<? super kotlin.Unit>);
field public static final com.google.android.horologist.auth.data.phone.tokenshare.impl.TokenBundleRepositoryImpl.Companion Companion;
}

public static final class TokenBundleRepositoryImpl.Companion {
method public <T> com.google.android.horologist.auth.data.phone.tokenshare.impl.TokenBundleRepositoryImpl<T> create(com.google.android.horologist.data.WearDataLayerRegistry registry, optional String key, kotlinx.coroutines.CoroutineScope coroutineScope, androidx.datastore.core.Serializer<T> serializer);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,9 @@ import com.google.android.horologist.auth.data.phone.ExperimentalHorologistAuthD
public interface TokenBundleRepository<T> {

public suspend fun update(tokenBundle: T)

/**
* Check if this repository is available to be used on this device.
*/
public suspend fun isAvailable(): Boolean
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,56 +16,75 @@

package com.google.android.horologist.auth.data.phone.tokenshare.impl

import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.core.Serializer
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.api.AvailabilityException
import com.google.android.horologist.auth.data.phone.ExperimentalHorologistAuthDataPhoneApi
import com.google.android.horologist.auth.data.phone.common.TAG
import com.google.android.horologist.auth.data.phone.tokenshare.TokenBundleRepository
import com.google.android.horologist.auth.data.phone.tokenshare.impl.TokenBundleRepositoryImpl.Companion.DEFAULT_TOKEN_BUNDLE_KEY
import com.google.android.horologist.data.WearDataLayerRegistry
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.tasks.await

/**
* Default implementation for [TokenBundleRepository].
*
* If multiple [token bundles][T] are required to be shared, specify a [key] in
* order to identify each one, otherwise the same [default][DEFAULT_TOKEN_BUNDLE_KEY] key
* will be used and only a single token bundle will be persisted.
*
* @sample com.google.android.horologist.auth.sample.MainActivity
*/
@ExperimentalHorologistAuthDataPhoneApi
public class TokenBundleRepositoryImpl<T>(
private val dataStore: DataStore<T>
private val registry: WearDataLayerRegistry,
private val key: String = DEFAULT_TOKEN_BUNDLE_KEY,
private val coroutineScope: CoroutineScope,
private val serializer: Serializer<T>
) : TokenBundleRepository<T> {

override suspend fun update(tokenBundle: T) {
dataStore.updateData { tokenBundle }
getDataStore()?.updateData { tokenBundle }
}

public companion object {
override suspend fun isAvailable(): Boolean {
return try {
GoogleApiAvailability.getInstance()
.checkApiAvailability(registry.dataClient)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure you like the God object of the registry, but if we push this up there, then it can be done once, at startup meaning it's immediately available so screen can draw correctly immediately.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be ideal to have these checks in WearDataLayerRegistry, not sure about having it immediately available, it would be an assumption about the time taken by play service lib to check it

raised #1091

.await()

private const val DEFAULT_TOKEN_BUNDLE_KEY = "/horologist_token_bundle"
true
} catch (e: AvailabilityException) {
Log.d(
TAG,
"DataClient API is not available in this device. TokenBundleRepository will fail silently and all functionality will be no-op."
)
false
}
}

/**
* Factory method for [TokenBundleRepositoryImpl].
*
* If multiple [token bundles][T] are required to be shared, specify a [key] in
* order to identify each one, otherwise the same [default][DEFAULT_TOKEN_BUNDLE_KEY] key
* will be used and only a single token bundle will be persisted.
*/
public fun <T> create(
registry: WearDataLayerRegistry,
key: String = DEFAULT_TOKEN_BUNDLE_KEY,
coroutineScope: CoroutineScope,
serializer: Serializer<T>
): TokenBundleRepositoryImpl<T> = TokenBundleRepositoryImpl(
private suspend fun getDataStore(): DataStore<T>? =
if (isAvailable()) {
registry.protoDataStore(
path = buildPath(key),
coroutineScope = coroutineScope,
serializer = serializer
)
)
} else {
null
}

private fun buildPath(key: String) =
if (key.startsWith("/")) {
key
} else {
"/$key"
}

private fun buildPath(key: String) =
if (key.startsWith("/")) {
key
} else {
"/$key"
}
public companion object {
private const val DEFAULT_TOKEN_BUNDLE_KEY = "/horologist_token_bundle"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,24 @@ import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.lifecycleScope
import com.google.android.horologist.auth.data.phone.tokenshare.TokenBundleRepository
Expand All @@ -55,13 +64,13 @@ class MainActivity : ComponentActivity() {
coroutineScope = lifecycleScope
)

tokenBundleRepositoryDefaultKey = TokenBundleRepositoryImpl.create(
tokenBundleRepositoryDefaultKey = TokenBundleRepositoryImpl(
registry = registry,
coroutineScope = lifecycleScope,
serializer = TokenBundleSerializer
)

tokenBundleRepositoryCustomKey = TokenBundleRepositoryImpl.create(
tokenBundleRepositoryCustomKey = TokenBundleRepositoryImpl(
registry = registry,
coroutineScope = lifecycleScope,
serializer = TokenBundleSerializer,
Expand All @@ -75,7 +84,16 @@ class MainActivity : ComponentActivity() {
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val coroutineScope = rememberCoroutineScope()
var apiAvailable by remember { mutableStateOf(false) }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's safe to do the operations, then I think defaulting to true. Or making this true/false/null would be better here. Avoid glitching the screen in the hopefully typical case where it is available.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it makes sense, and it would be better to have this in a VM, and have proper states

this sample app is very simple, in comparison to the wear counterpart, it's in my plans to improve it further and will address it together

LaunchedEffect(Unit) {
coroutineScope.launch {
apiAvailable = tokenBundleRepositoryDefaultKey.isAvailable()
}
}

MainScreen(
apiAvailable = apiAvailable,
onUpdateTokenDefault = ::onUpdateTokenDefault,
onUpdateTokenCustom = ::onUpdateTokenCustom
)
Expand Down Expand Up @@ -107,6 +125,7 @@ class MainActivity : ComponentActivity() {

@Composable
fun MainScreen(
apiAvailable: Boolean,
onUpdateTokenDefault: () -> Unit,
onUpdateTokenCustom: () -> Unit,
modifier: Modifier = Modifier
Expand All @@ -120,15 +139,26 @@ fun MainScreen(
onClick = {
onUpdateTokenDefault()
},
modifier = Modifier.wrapContentHeight()
modifier = Modifier.wrapContentHeight(),
enabled = apiAvailable
) { Text(stringResource(R.string.token_share_button_update_token_default)) }

Button(
onClick = {
onUpdateTokenCustom()
},
modifier = Modifier.wrapContentHeight()
modifier = Modifier.wrapContentHeight(),
enabled = apiAvailable
) { Text(stringResource(R.string.token_share_button_update_token_custom)) }

if (!apiAvailable) {
Text(
text = stringResource(R.string.token_share_message_api_unavailable),
modifier.fillMaxWidth(),
color = Color.Red,
textAlign = TextAlign.Center
)
}
}
}

Expand All @@ -137,6 +167,7 @@ fun MainScreen(
fun GreetingPreview() {
HorologistTheme {
MainScreen(
apiAvailable = true,
onUpdateTokenDefault = { },
onUpdateTokenCustom = { }
)
Expand Down
1 change: 1 addition & 0 deletions auth-sample-phone/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
<string name="app_name">Horologist Auth Sample</string>
<string name="token_share_button_update_token_default">Update token - default key</string>
<string name="token_share_button_update_token_custom">Update token - custom key</string>
<string name="token_share_message_api_unavailable">This device does not have capability to communicate to Wearable Data Layer API</string>
</resources>