Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,26 @@ query GetItemByKey(
}
}

query GetAllItems @auth(level: PUBLIC) {
items: zwda6x9zyys {
id
string
int
int64
float
boolean
date
timestamp
any
}
}

mutation DeleteItemByKey(
$key: zwda6x9zyy_Key!
) @auth(level: PUBLIC) {
zwda6x9zyy_delete(key: $key)
}

# This mutation exists only as a workaround for b/382688278 where the following
# compiler error will otherwise result when compiling the generated code:
# Serializer has not been found for type 'java.util.UUID'. To use context
Expand Down
10 changes: 7 additions & 3 deletions firebase-dataconnect/demo/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@ See the License for the specific language governing permissions and
limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<application
android:name=".MyApplication"
android:label="Data Connect Minimal Demo"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:theme="@style/Theme.AppCompat"
>

<activity android:name=".MainActivity" android:exported="true">
Expand All @@ -32,6 +31,11 @@ limitations under the License.
</intent-filter>
</activity>

<activity
android:name=".ListItemsActivity"
android:label="List Items"
/>

</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.dataconnect.minimaldemo

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.dataconnect.minimaldemo.connector.GetAllItemsQuery
import com.google.firebase.dataconnect.minimaldemo.databinding.ActivityListItemsBinding
import com.google.firebase.dataconnect.minimaldemo.databinding.ListItemBinding
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class ListItemsActivity : AppCompatActivity() {

private lateinit var myApplication: MyApplication
private lateinit var viewBinding: ActivityListItemsBinding
private val viewModel: ListItemsViewModel by viewModels { ListItemsViewModel.Factory }

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
myApplication = application as MyApplication

viewBinding = ActivityListItemsBinding.inflate(layoutInflater)
viewBinding.recyclerView.also {
val linearLayoutManager = LinearLayoutManager(this)
it.layoutManager = linearLayoutManager
val dividerItemDecoration = DividerItemDecoration(this, linearLayoutManager.layoutDirection)
it.addItemDecoration(dividerItemDecoration)
}
setContentView(viewBinding.root)

lifecycleScope.launch {
if (viewModel.loadingState == ListItemsViewModel.LoadingState.NotStarted) {
viewModel.getItems()
}
viewModel.stateSequenceNumber.flowWithLifecycle(lifecycle).collectLatest {
onViewModelStateChange()
}
}
}

private fun onViewModelStateChange() {
val items = viewModel.result?.getOrNull()
val exception = viewModel.result?.exceptionOrNull()
val loadingState = viewModel.loadingState

if (loadingState == ListItemsViewModel.LoadingState.InProgress) {
viewBinding.statusText.text = "Loading Items..."
viewBinding.statusText.visibility = View.VISIBLE
viewBinding.recyclerView.visibility = View.GONE
viewBinding.recyclerView.adapter = null
} else if (items !== null) {
viewBinding.statusText.text = null
viewBinding.statusText.visibility = View.GONE
viewBinding.recyclerView.visibility = View.VISIBLE
val oldAdapter = viewBinding.recyclerView.adapter as? RecyclerViewAdapterImpl
if (oldAdapter === null || oldAdapter.items !== items) {
viewBinding.recyclerView.adapter = RecyclerViewAdapterImpl(items)
}
} else if (exception !== null) {
viewBinding.statusText.text = "Loading items FAILED: $exception"
viewBinding.statusText.visibility = View.VISIBLE
viewBinding.recyclerView.visibility = View.GONE
viewBinding.recyclerView.adapter = null
} else {
viewBinding.statusText.text = null
viewBinding.statusText.visibility = View.GONE
viewBinding.recyclerView.visibility = View.GONE
}
}

private class RecyclerViewAdapterImpl(val items: List<GetAllItemsQuery.Data.ItemsItem>) :
RecyclerView.Adapter<RecyclerViewViewHolderImpl>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewViewHolderImpl {
val binding = ListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return RecyclerViewViewHolderImpl(binding)
}

override fun getItemCount() = items.size

override fun onBindViewHolder(holder: RecyclerViewViewHolderImpl, position: Int) {
holder.bindTo(items[position])
}
}

private class RecyclerViewViewHolderImpl(private val binding: ListItemBinding) :
RecyclerView.ViewHolder(binding.root) {

fun bindTo(item: GetAllItemsQuery.Data.ItemsItem) {
binding.id.text = item.id.toString()
binding.name.text = item.string
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.dataconnect.minimaldemo

import android.util.Log
import androidx.annotation.MainThread
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.google.firebase.dataconnect.minimaldemo.connector.GetAllItemsQuery
import com.google.firebase.dataconnect.minimaldemo.connector.execute
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ListItemsViewModel(private val app: MyApplication) : ViewModel() {

// Threading Note: _state and the variables below it may ONLY be accessed (read from and/or
// written to) by the main thread; otherwise a race condition and undefined behavior will result.
private val _stateSequenceNumber = MutableStateFlow(111999L)
val stateSequenceNumber: StateFlow<Long> = _stateSequenceNumber.asStateFlow()

var result: Result<List<GetAllItemsQuery.Data.ItemsItem>>? = null
private set

private var job: Job? = null
val loadingState: LoadingState =
job.let {
if (it === null) {
LoadingState.NotStarted
} else if (it.isCancelled || it.isCompleted) {
LoadingState.Completed
} else {
LoadingState.InProgress
}
}

enum class LoadingState {
NotStarted,
InProgress,
Completed,
}

@OptIn(ExperimentalCoroutinesApi::class)
@MainThread
fun getItems() {
// If there is already a "get items" operation in progress, then just return and let the
// in-progress operation finish.
if (loadingState == LoadingState.InProgress) {
return
}

// Start a new coroutine to perform the "get items" operation.
val job: Deferred<List<GetAllItemsQuery.Data.ItemsItem>> =
viewModelScope.async { app.getConnector().getAllItems.execute().data.items }

this.result = null
this.job = job
_stateSequenceNumber.value++

// Update the internal state once the "get items" operation has completed.
job.invokeOnCompletion { exception ->
// Don't log CancellationException, as documented by invokeOnCompletion().
if (exception is CancellationException) {
return@invokeOnCompletion
}

val result =
if (exception !== null) {
Log.w(TAG, "WARNING: Getting all items FAILED: $exception", exception)
Result.failure(exception)
} else {
val items = job.getCompleted()
Log.i(TAG, "Retrieved all items ${items.size} items")
Result.success(items)
}

viewModelScope.launch {
if ([email protected] === job) {
[email protected] = result
[email protected] = null
_stateSequenceNumber.value++
}
}
}
}

companion object {
private const val TAG = "ListItemsViewModel"

val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer { ListItemsViewModel(this[APPLICATION_KEY] as MyApplication) }
}
}
}
Loading
Loading