android - 如何在 jetpack compose 中传递来自 Firestore 的查询的参数
问题描述
我的项目中有一个查询来检索游戏列表并将其显示在一个lazyColumn 中。当我查询整个集合时它工作正常,但我想放置一个 whereIn 子句,它需要我必须在片段中传递的 2 个参数,但我不知道如何使用 Jetpack Compose 传递它。
以下是已经存在且正在运行的查询:
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Named("queryGame")
fun provideGetAllGames(): Query =
FirebaseFirestore.getInstance()
.collection(GAMES)
}
@Singleton
class PlayersRepository @Inject constructor(
private val queryGame: Query,
) {
fun getPlayerFromFirestore(): DataOrException<Task<DocumentSnapshot>, Exception> {
val dataOrException = DataOrException<Task<DocumentSnapshot>, Exception>()
try {
dataOrException.data = getUser.get()
} catch (e: FirebaseFirestoreException) {
dataOrException.e = e
}
return dataOrException
}
@HiltViewModel
class GamesViewModel @Inject constructor(
private val repository: PlayersRepository
): ViewModel() {
val data: MutableState<DataOrException<List<Game>, Exception>> = mutableStateOf(
DataOrException(
listOf(),
Exception("")
)
)
init{
getAllGames()
}
fun getAllGames() {
viewModelScope.launch {
data.value = repository.getAllGames()
}
}
@AndroidEntryPoint
class GameFragment : Fragment() {
private val viewModel: GamesViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
val games = viewModel.data.value.data
LazyColumn{
items(games!!){ game ->
GameResults(game)
}
}
我需要在 appModule 中添加 .whereIn(PLAYERS, listOf(user1 + " " + user2, user2 + " " + user1)) 但我不知道如何在片段上传递 user1 和 user2。我怎样才能做到这一点?
解决方案
我需要在 appModule 中添加 .whereIn(PLAYERS, listOf(user1 + "" + user2, user2 + "" + user1))
您不能将动态数据传递到 AppModule 文件中。因此,要使用 Query 对象从 Firestore 获取数据,您需要.whereIn()
在存储库类中添加该调用。看到您已经将“queryGame”对象(实际上是一个 CollectionReference 对象)注入到您的存储库类中,您可以使用以下代码行:
dataOrException.data = queryGame.whereIn(PLAYERS, listOf(user1 + "" + user2, user2 + "" + user1)).get()
不要忘记在使用此查询的方法中同时传递“user1”和“user2”对象。
推荐阅读
- python - 在调用不带括号的类实例时返回一个对象
- ruby-on-rails - 如何将 Rails 模型文件拆分为多个文件(不是关注点,不是模块,只是单独的文件)?
- python - Python:调用另一个被调用函数内部的函数时出现问题
- reactjs - 如何在 ReactJS 中设置或控制从数组的列表/键中保存的元素?
- ios - CSSearchableAttributeset supportPhoneCall,导航不起作用
- javascript - 使用 Chrome/Chromium 使用 WWW::Mechanize::Chrome 从服务器获取“原始”jss 和 css 代码
- reactjs - SafeAreaView 未填充手机头部区域
- kubernetes - Pod 与绑定本地持久卷的主机节点的亲和性
- python - 使用火花将每行中的值转换为新列
- python-3.x - 需要获取包含在类中的文本