@HiltAndroidApp
class MelonFeedApp: Application() {
override fun onCreate() {
super.onCreate()
FirebaseDatabase.getInstance().setPersistenceEnabled(true)
}
}
MelonFeedApp.kt
class UserRepositoryImpl @Inject constructor(
private val db: FirebaseDatabase,
private val auth: FirebaseAuth
): UserRepository {
private lateinit var userRef: DatabaseReference
init {
auth.currentUser?.let {
userRef = db.getReference("users/${it.uid}")
userRef.keepSynced(true)
}
}
// methods
}
UserRepositoryImpl.kt
@HiltViewModel
class ProfileViewModel @Inject constructor(
context: Context,
private val userRepository: UserRepository,
private val auth: FirebaseAuth
) : ViewModel() {
private val _profilePic = MutableLiveData<Bitmap?>()
val profilePic: LiveData<Bitmap?> = _profilePic
init {
viewModelScope.launch {
val imageData = getUserProfileImage()
if (imageData != null) {
val bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.size)
_profilePic.value = bitmap
} else {
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.profilepc)
_profilePic.value = bitmap
}
}
}
fun updateProfilePic(bitmap: Bitmap) {
_profilePic.value = bitmap
}
private suspend fun getUserData(fieldName: String) {
return withContext(Dispatchers.IO) {
try {
userRepository.getCurrentUserData(fieldName)
} catch (_: Exception) {
}
}
}
private suspend fun getUserProfileImage(): ByteArray? {
val storageReference = FirebaseStorage.getInstance().reference
val profileImageReference = storageReference.child("profile_images/profilePicture_${auth.currentUser?.uid}")
return profileImageReference.getBytes(2 * 1024 * 1024 * 1024L).await()
}
}
ProfileViewModel.kt
我已经在 MelonFeedApp.kt 中启用了 diskPersistense,并且在 UserRepositoryImpl.kt 中打开了 keepSynced,但如果我关闭网络连接,它仍然不会加载个人资料图片。
请帮助我使用 Firebase 缓存。我已经尝试了几天了,但我仍然无法弄清楚。
如果我关闭网络连接,则不会加载个人资料图片。
如果您想缓存数据和图片,那么您必须使用库。由于您使用的是 Jetpack Compose,因此一个不错的选择是使用 Coil,即:
由 Kotlin 协程支持的 Android 图像加载库。
并且可以通过添加以下依赖项与 Jetpack Compose 一起使用:
implementation("io.coil-kt:coil-compose:2.6.0")