@OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)
@Composable
fun ProfileScreen(
navigate: (String) -> Unit,
viewModel: ProfileViewModel = hiltViewModel()
) {
// code
val result by viewModel.profilePicUrl.collectAsState()
// code
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
GlideImage(
model = result,
contentDescription = null,
modifier = Modifier
.size(170.dp, 170.dp)
.clip(CircleShape)
.clickable {
showBottomSheet = true
},
) { image ->
image
.fitCenter()
.circleCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.profilepic)
}
// button
}
// some more code
}
This is my UI
@HiltViewModel
class ProfileViewModel @Inject constructor(
// dependencies
) : ViewModel() {
private val _profilePicUrl = MutableStateFlow("")
val profilePicUrl: StateFlow<String> = _profilePicUrl
init {
viewModelScope.launch {
_profilePicUrl.value = getUserData("profileImage").toString()
}
}
fun updateProfilePic(bitmap: Bitmap) {
viewModelScope.launch {
uploadImageToFirebase(bitmap)
}
}
private suspend fun getUserData(fieldName: String): Any? {
return withContext(Dispatchers.IO) {
try {
userRepository.getCurrentUserData(fieldName)
} catch (_: Exception) {
null
}
}
}
private suspend fun saveUserData(fieldName: String, data: Any): Boolean {
return userRepository.saveUserData(fieldName, data)
}
private suspend fun uploadImageToFirebase(imageUri: Bitmap) {
userRepository.uploadImageToFirebaseStorage(imageUri)
_profilePicUrl.emit(getUserData("profileImage").toString())
}
fun removeProfilePicture() {
// code
}
private fun getRandomDefaultImage(): String {
val randomImages = arrayOf(
// 2 links
)
return randomImages.random()
}
}
ViewModel
@HiltAndroidApp
class MelonFeedApp : Application() {
override fun onCreate() {
super.onCreate()
Glide.with(this)
.applyDefaultRequestOptions(RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL))
}
}
ApplicationClass
Here, I want that when the user has no internet then also his profile picture loads in the app from cache. For caching I’m using Glide but it doesn’t work as expected. The image doesn’t load when there’s no internet. The image does load if there is internet.
I’d be glad if someone helped 🙂
Please help
Thank You,
Vedant