I have a TodoList App and I have a reminder feature in the fragment where you add your Todo, Meanwhile in another fragment the set Reminder is shown for that particular Task that was created. I want to be able to change the color of the Reminder to red when the Alarm set by the USER is Overdue or has been triggered. I was able to do the first but not the second. Is there a way I can check if the Alarm for that Todo has been Triggered(because the color for the second situation only changes when I recreate the view) in REAL TIME and then update it in the ListFragment changing the color of the Alarm to red. The Solutions I have tried in Stack Overflow here don't seem to work and is in a different language.
A picture of it.
My Alarm and Notifications code in my AddFragment
private fun scheduleNotification() {
val title = binding.edTaskTitle.text.toString()
val intent = Intent(requireContext().applicationContext , Notifications::class.java).apply {
putExtra(TITLE_EXTRA, title)
}
val pendingIntent = PendingIntent.getBroadcast(
requireContext().applicationContext,
NOTIFICATION_ID,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val alarmManager = requireContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
setDateTime,
pendingIntent
)
}
This is my bind function in my Adapter(My Adapter is in a separate file from my Fragment). In my Adapter is where I wrote the Implementation for changing the color of the reminder text if the Initial reminder set by the User is past the current Time(Overdue).
#SuppressLint("DiscouragedPrivateApi")
fun bind(todo : Todo) {
val dateLocales = SimpleDateFormat(SIMPLE_DATE_FORMAT, Locale.getDefault())
val timeLocales = SimpleDateFormat(SIMPLE_TIME_FORMAT, Locale.getDefault())
binding.apply {
tvTaskTitle.text = todo.title
tvTaskDate.text = dateLocales.format(todo.date)
tvTaskTime.text = timeLocales.format(todo.time)
cbTask.isChecked = todo.completed
tvTaskTitle.paint.isStrikeThruText = todo.completed
tvResultsReminder.isVisible = todo.important
// Will only show the resultsReminder if important is true
if (todo.important) {
tvResultsReminder.text = DateUtils.getRelativeDateTimeString(_context, todo.reminder.time, DateUtils.DAY_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0)
val date = Date()
val drawable : Drawable? = ContextCompat.getDrawable(_context, R.drawable.ic_alarm_reminder)
if (todo.reminder.time < date.time) {
tvResultsReminder.setTextColor(ContextCompat.getColor(_context, R.color.red))
}
}
// Implementing our PopupMenus to Edit and Delete a Task
iMenus.setOnClickListener { view ->
val popupMenus = PopupMenu(_context, view)
popupMenus.inflate(R.menu.show_menu)
popupMenus.setOnMenuItemClickListener {
when(it.itemId) {
R.id.itEditTask -> {
val action = ListFragmentDirections.actionListFragmentToUpdateFragment(todo)
itemView.findNavController().navigate(action)
true
}
R.id.itDeleteTask -> {
val position = adapterPosition// this represents the position of any item in the root layout
// NO_POSITION means that an item is invalid and out of this list, so this is a safe check because-
// we don't want to call a listener on an invalid item
if (position != RecyclerView.NO_POSITION) {
val curTodo = getItem(position)
listener.onItemDelete(curTodo)
}
Toast.makeText(_context, "Task has been deleted.", Toast.LENGTH_LONG).show()
true
}
else -> true
}
}
popupMenus.show()
val popup = PopupMenu::class.java.getDeclaredField("mPopup")
popup.isAccessible = true
val menu = popup.get(popupMenus)
menu.javaClass.getDeclaredMethod("setForceShowIcon", Boolean::class.java)
.invoke(menu, true)
}
}
}
}
And then I passed in a Column "triggered" in my Todo Class to record the state of the triggered Alarm to know what to do as the supposed Solution.
#Parcelize
#Entity(tableName = "todo_table")
data class Todo(
#PrimaryKey (autoGenerate = true) // here "Room" will autoGenerate the id for us instead of assigning a randomUUID value
val id : Int = 0,
val title : String = "",
var date : Date = Date(),
var time : Date = Date(),
var reminder : Date = Date(),
var important : Boolean = false,
var completed : Boolean = false,
val triggered : Boolean = false,
val created : Long = System.currentTimeMillis()
) : Parcelable
Another issue is that even I were able to do this. How would I in REAL TIME without recreating the view or doing something else be aware that the state of the Triggered alarm has been changed to then change the color of the text. It just seems so difficult.
Related
in my ViewModel:
private val _itemList = mutableStateListOf<Post>()
val itemList: List<Post> = _itemList
fun likePost(newPost: Post){
val index = _itemList.indexOf(newPost)
_itemList[index] = _itemList[index].copy(isLiked = true)
}
Here my Post data class:
data class Post(
val id: Int,
val name: String,
val isLiked: Boolean = false,
)
And here my Composable:
val postList = viewModel.itemList
LazyRow(content = {
items(postList.size) { i ->
val postItem = postList[i]
PostItem(
name = postItem.name,
isLiked = postItem.isLiked,
likePost = { viewModel.likePost(postItem)}
)
}
})
The change does not update in the UI instantly, I first have to scroll the updated item out of the screen so it recomposes or switch to another Screen and go back to see the change.
For some reason it doesn't like updating, it will add and delete and update instantly. You have to do it this way when updating for our to update the state.
fun likePost(newPost: Post){
val index = _itemList.indexOf(newPost)
_itemList[index] = _itemList[index].copy()
_itemList[index].isLiked = true
}
You are returning a List<> effectively and not MutableStateList from your ViewModel.
If you want the list to not be mutable from the view, I happen to use MutableStateFlow<List<>> and return StateFlow<List<>>. You could also just convert it to a list in your composable.
Edit:
//backing cached list, or could be data source like database
private val deviceList = mutableListOf<Device>()
private val _deviceListState = MutableStateFlow<List<Device>>(emptyList())
val deviceListState: StateFlow<List<BluetoothDevice>> = _deviceListState
//manipulate and publish
fun doSomething() {
_deviceListState.value = deviceList.filter ...
}
In your UI
val deviceListState = viewModel.deviceListState.collectAsState().value
I'm trying to display a 4x4 grid with values that change depending on user input. To achieve that, I created mutableStateListOf that I use in a ViewModel to survive configuration changes. However, when I try to replace a value in that particular list using button onClick, it keeps doing that until app crashes. I can't understand why is onReplaceGridContent looping after clicking the button once. Currently, my code looks like this:
ViewModel:
class GameViewModel : ViewModel(){
var gameGridContent = mutableStateListOf<Int>()
private set // Restrict writes to this state object to private setter only inside view model
fun replaceGridContent(int: Int, index: Int){
gameGridContent[index] = int
}
fun removeGridContent(index: Int){
gameGridContent[index] = -1
}
fun initialize(){
for(i in 0..15){
gameGridContent.add(-1)
}
val firstEmptyGridTile = GameUtils.getRandomTilePosition(gameGridContent)
val firstGridNumber = GameUtils.getRandomTileNumber()
gameGridContent[firstEmptyGridTile] = firstGridNumber
}
}
Button:
Button(
onClick = {
onReplaceGridContent(GameUtils.getRandomTileNumber(),GameUtils.getRandomTilePosition(gameGridContent))},
colors = Color.DarkGray
){
Text(text = "Add number to tile")
}
Activity Composable:
#Composable
fun gameScreen(gameViewModel: GameViewModel){
gameViewModel.initialize()
MainStage(
gameGridContent = gameViewModel.gameGridContent,
onReplaceGridContent = gameViewModel::replaceGridContent,
onRemoveGridContent = gameViewModel::removeGridContent
)
}
Your initialize will actually run on every recomposition of gameScreen:
You click on a tile - state changes causing recomposition.
initializa is called and changes the state again causing recomposition.
Step 2 happens again and again.
You should initialize your view model in its constructor instead (or use boolean flag to force one tim initialization) to make it inly once.
Simply change it to constructor:
class GameViewModel : ViewModel(){
var gameGridContent = mutableStateListOf<Int>()
private set // Restrict writes to this state object to private setter only inside view model
fun replaceGridContent(int: Int, index: Int){
gameGridContent[index] = int
}
fun removeGridContent(index: Int){
gameGridContent[index] = -1
}
init {
for(i in 0..15){
gameGridContent.add(-1)
}
val firstEmptyGridTile = GameUtils.getRandomTilePosition(gameGridContent)
val firstGridNumber = GameUtils.getRandomTileNumber()
gameGridContent[firstEmptyGridTile] = firstGridNumber
}
}
Now you don't need to call initialize in the composable:
#Composable
fun gameScreen(gameViewModel: GameViewModel){
MainStage(
gameGridContent = gameViewModel.gameGridContent,
onReplaceGridContent = gameViewModel::replaceGridContent,
onRemoveGridContent = gameViewModel::removeGridContent
)
}
I declared variable like this.
var saleData: MutableLiveData<SaleData> = MutableLiveData()
data class
data class SaleData(
var saleType: Int,
var saleDetail: Int,
var salePrice: Int,
var saleRate: Int,
var printAmount: Int
)
and then, init the data
init {
saleData.value = SaleData(saleType = 1, saleDetail = 0, salePrice = 0, saleRate = 0, printAmount = 1)
}
The question is, if one of the components of the data class in SaleData changes, can I be notified of this?
I simply wrote the code as below, but there was no result value.
viewModel
fun changeData() {
saleData.value?.saleRate = 50
}
fragment - at onCreateView
binding.viewModel = viewModel
binding.lifecycleOwner = this
viewModel.saleData.observe(viewLifecycleOwner, Observer { saleData ->
Log.d(TAG,"value changed")
})
I can't get the Log when change the saleRate in saleData
Like this code,
saleData.value = SaleData(saleType = saleType, saleDetail = 0, salePrice = 0, saleRate = 0, printAmount = 1)
I set saleData value, it notify the value changed but I want when change the item of saleData, notify the change
Is there anything else I need to set up?
A call to saleData.value?.saleRate = 50 will not notify observers because the underlying object stored within the MutableLiveData remains unchaged. For LiveData to notify its observers, you need to assign a new object to it.
Assuming SaleData is a data class, you can make it notify it's observers by calling,
saleData.value = saleData.value?.copy(saleRate = 50)
This will notify all registered observers.
As Rafsanjani said, you need to assign an updated reference of the SaleData class to the LiveData. Once you do that, the LiveData observer will notify the changes. For better understanding, please, see the code below.
SaleDataViewModel
class SaleDataViewModel: ViewModel() {
private var _saleData: MutableLiveData<SaleData> = MutableLiveData()
val saleData: LiveData<SaleData> = _saleData
init {
_saleData.value = SaleData(saleType = 1, saleDetail = 0, salePrice = 0, saleRate = 0, printAmount = 1)
}
fun updateSale() {
val saleRate = updatedSaleRate()
_saleData.value = SaleData( _saleData.value!!.saleType, _saleData.value!!.saleDetail, _saleData.value!!.salePrice, saleRate, _saleData.value!!.printAmount)
}
private fun updatedSaleRate(): Int {
return 50
}
}
SaleDataFragment
class SaleDataFragment: Fragment() {
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) {
viewModel.updateSale()
viewModel.saleData.observe(viewLifecycleOwner, Observer {
Log.d(TAG, "Notify change")
})
}
}
The fragment I am coding right now is supposed to give the user a calendaric overview of his meal planning schedule. So via date picker, he can choose a time period and the program will show the user which recipes he has chosen for the chosen weekdays.
So I build a nested RecyclerView with the weekdays as parent layer and corresponding recipes as a child layer. The data class for the weekday layer looks like this :
data class Weekday (
val weekday : String,
val listWithRecipes : List<Recipe>?
)
The class for the Recipe entity looks like this:
#Entity(tableName = "Recipe")
#Parcelize
data class Recipe(
#PrimaryKey var recipeName : String,
var description : String?,
var serving : Int,
var preparationTime : Int?
) : Parcelable
The Adapter for the top Recycler View like this :
class MealPlanAdapter(private var mealplan: List<Weekday>) :
RecyclerView.Adapter<MealPlanAdapter.MealPlanViewHolder>(), RecipeAdapter.OnItemClickListener {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MealPlanViewHolder {
return MealPlanViewHolder(
DailyMealplanItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun getItemCount() = mealplan.size
override fun onBindViewHolder(holder: MealPlanViewHolder, position: Int) {
val weekday = mealplan[position]
val recipeAdapter = RecipeAdapter(this)
recipeAdapter.submitList(weekday?.listWithRecipes)
holder.dayOfWeek.text = weekday.weekday
val recipeLayoutManager = LinearLayoutManager(holder.recyclerView.context,RecyclerView.VERTICAL, false)
recipeLayoutManager.initialPrefetchItemCount = 4
holder.recyclerView.apply{
layoutManager = recipeLayoutManager
adapter = recipeAdapter
}
}
fun setSchedule(mealplan : List <Weekday>){
this.mealplan = mealplan
notifyDataSetChanged()
}
inner class MealPlanViewHolder(val binding: DailyMealplanItemBinding) :
RecyclerView.ViewHolder(binding.root) {
val recyclerView: RecyclerView = binding.rvRecyclerView
val dayOfWeek: TextView = binding.tvDayOfWeek
}
override fun onItemClick(recipe: Recipe) {
TODO("Not yet implemented")
}
}
Whenever the user changes the time period, the setScheduled() method in the adapter gets called in the fragment.
materialDatePickerStartDate.addOnPositiveButtonClickListener(
MaterialPickerOnPositiveButtonClickListener<Any?> { selection ->
_binding.viewmodel!!.startDateInUTCFormat = selection as Long
_binding.tvStartDate.setText(materialDatePickerStartDate.headerText)
adapter.setSchedule(
_binding.viewmodel!!.returnListWithWeekDaysAndCorrespondingRecipes(
_binding.viewmodel!!.startDateInUTCFormat,
_binding.viewmodel!!.endDateInUTCFormat
)
)
}
)
The viewmodel looks like this :
#HiltViewModel
class MealplanViewModel #Inject constructor(
val mealPlanRepository: MealPlanRepository
) : ViewModel() {
private lateinit var _binding: FragmentMealPlanBinding
var startDateInUTCFormat: Long = System.currentTimeMillis()
var endDateInUTCFormat: Long = System.currentTimeMillis()
fun returnListWithWeekDaysAndCorrespondingRecipes(
startDate: Long,
endDate: Long
): ArrayList<Weekday> {
var startDate = Date(startDateInUTCFormat)
var endDate = Date(endDateInUTCFormat)
var startDateCalendar = dateToCalendar(startDate)
var endDateCalendar = dateToCalendar(endDate)
val calendarDays = createListWithCalendarDates(startDateCalendar, endDateCalendar)
return createListWithWeekDaysAndCorrespondingRecipes(calendarDays)
}
fun dateToCalendar(date: Date): Calendar {
var calInstance = Calendar.getInstance()
calInstance.setTime(date)
return calInstance
}
fun createListWithCalendarDates(
startDateCalendar: Calendar,
endDateCalendar: Calendar
): ArrayList<Calendar> {
var listWithCalendarDates = arrayListOf<Calendar>()
while (startDateCalendar <= endDateCalendar) {
listWithCalendarDates.add(startDateCalendar.clone() as Calendar)
startDateCalendar.add(Calendar.DATE, 1)
}
return listWithCalendarDates
}
fun createListWithWeekDaysAndCorrespondingRecipes(calendarDays: ArrayList<Calendar>): ArrayList<Weekday> {
var dayOfWeekAsString: String
var listWithDaysOfWeeksAndRecipes = arrayListOf<Weekday>()
var flattenedListWithRecipes: List<Recipe>?
for (i in 0 until calendarDays.size) {
var dayOfWeekAsInt = calendarDays[i].get(Calendar.DAY_OF_WEEK)
dayOfWeekAsString = when (dayOfWeekAsInt) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
else -> "Saturday"
}
var calendarDateInString =
transformCalendarDateIntoRequiredStringFormat(calendarDays[i])
var listWithDateAndCorrespondingRecipes: List<MealplanScheduleWithRecipes> =
listOf()
var liveDatalistWithDateAndCorrespondingRecipes =
mealPlanRepository.getMealplanScheduleWithRecipes(calendarDateInString)
liveDatalistWithDateAndCorrespondingRecipes.observeForever() { list ->
listWithDateAndCorrespondingRecipes = list
var listWithRecipes = listWithDateAndCorrespondingRecipes?.map { it.recipes }
flattenedListWithRecipes = listWithRecipes?.flatten()
var wochentag = dayOfWeekAsString
listWithDaysOfWeeksAndRecipes.add(Weekday(dayOfWeekAsString, flattenedListWithRecipes))
}
}
return listWithDaysOfWeeksAndRecipes
}
fun transformCalendarDateIntoRequiredStringFormat(calendarDate: Calendar): String {
var year = calendarDate.get(Calendar.YEAR)
var month = transformCalendarMonthFormatToCorrectMonth(calendarDate)
var day = calendarDate.get(Calendar.DAY_OF_MONTH)
return "$day" + "$month" + "$year"
}
fun transformCalendarMonthFormatToCorrectMonth(calendarDate: Calendar): String {
var monthCalendarFormat = calendarDate.get(Calendar.MONTH)
var monthCorrectFormat = when (monthCalendarFormat) {
0 -> "1"
1 -> "2"
2 -> "3"
3 -> "4"
4 -> "5"
5 -> "6"
6 -> "7"
7 -> "8"
8 -> "9"
9 -> "10"
10 -> "11"
else -> "12"
}
return monthCorrectFormat
}
fun datesAreReasonable(startDate: Long, endDate: Long): Boolean {
return (startDate <= endDate)
}
}
My problem is the list that is passed to the RecyclerView Adapter consists of Weekday objects, which consist of the name of the weekday and the corresponding recipes (see data class "weekday" on top).
In the method "createListWithWeekDaysAndCorrespondingRecipes" in the viewmodel I create this list in a for loop that gets all weekdays between given Dates and their corresponding recipes. However, the recipes are LiveData fetched asynchronously via Room database query while the names of the weekdays are derived synchronously in the main thread. At the end however when I create the Weekday object
(see listWithDaysOfWeeksAndRecipes.add(Weekday(dayOfWeekAsString, flattenedListWithRecipes) at the end of the for loop) I need them together at the same time. I haven't found a way how I can coordinate this successfully. At the moment the logics for adding the object to the list is in the asynchronous "observeForever" block.
See here:
liveDatalistWithDateAndCorrespondingRecipes.observeForever() { list ->
listWithDateAndCorrespondingRecipes = list
var listWithRecipes = listWithDateAndCorrespondingRecipes?.map { it.recipes }
flattenedListWithRecipes = listWithRecipes?.flatten()
var wochentag = dayOfWeekAsString
listWithDaysOfWeeksAndRecipes.add(Weekday(dayOfWeekAsString, flattenedListWithRecipes))
}
This creates wrong results, probably because the coordination between main thread and the observer thread doesn't work.
If I however take the logics of adding out of the observer block, the list with recipes will give me null, because of the asynchronous character of the query.
I know that I described the problem very badly. Maybe still someone got a grasp of it and can help?
You should try to avoid using observeForever, I expect you are using this inside a fragment or an activity which actually has a lifecyclescope that your observer can use.
Your observer should look something like this
liveDataList.observe(viewLifecycleOwner, { list ->
// The way I do it at the moment I just set the recyclerViews adapter and layoutManager here
// This is not the best way to do it, so please keep that in mind
recyclerView.apply {
adapter = MyAdapter(list)
layoutManager = LinearLayoutManager(requireContext())
}
})
// Or if used inside an activity
liveDataList.observe(this, {})
This way your observer will be attached to your lifecycle and "die" together with your view. Whenever that list changes, you will show all entities in the recyclerView. HOWEVER, when you use an Array together with LiveData the LiveData object never "updates" when you just add something to that value, since the array only is a memory reference to the start of the array.
To counter this whenever you add something to your array you need to refresh the LiveData object in order to trigger an update and all observers.
myLiveDataObject.value.add(someOtherObject)
myLiveDataObject.value = myLiveDataObject.value
myLiveDataObject.value = myLiveDataObject.value triggers all observers that there has been a change, annoying I know
If you use it inside a viewHolder or adapter simply pass the lifecycle along with the list
I am also quite new to kotlin, keep that in mind and I guarantee you there is a better way to do this, but hope it helps
In my Weather app, I have a MainFragment which has a button that opens a different fragment (SearchFragment) (via replace), allows a user to select a location and then fetches weather data for that location and loads it in various views including an MPAndroid LineChart. My issue is that whenever I come back from the search fragment, although the new data is fetched for the chart and I'm calling chart.notifyDataSetChanged() & chart.invalidate() (also tried chart.postInvalidate() since it was suggested when working on another thread) after the invalidate() is called the chart simply disappears. What am i missing here?
MainFragment:
const val UNIT_SYSTEM_KEY = "UNIT_SYSTEM"
const val LATEST_CURRENT_LOCATION_KEY = "LATEST_CURRENT_LOC"
class MainFragment : Fragment() {
// Lazy inject the view model
private val viewModel: WeatherViewModel by viewModel()
private lateinit var weatherUnitConverter: WeatherUnitConverter
private val TAG = MainFragment::class.java.simpleName
// View declarations
...
// OnClickListener to handle the current weather's "Details" layout expansion/collapse
private val onCurrentWeatherDetailsClicked = View.OnClickListener {
if (detailsExpandedLayout.visibility == View.GONE) {
detailsExpandedLayout.visibility = View.VISIBLE
detailsExpandedArrow.setImageResource(R.drawable.ic_arrow_up_black)
} else {
detailsExpandedLayout.visibility = View.GONE
detailsExpandedArrow.setImageResource(R.drawable.ic_down_arrow)
}
}
// OnClickListener to handle place searching using the Places SDK
private val onPlaceSearchInitiated = View.OnClickListener {
(activity as MainActivity).openSearchPage()
}
// RefreshListener to update the UI when the location settings are changed
private val refreshListener = SwipeRefreshLayout.OnRefreshListener {
Toast.makeText(activity, "calling onRefresh()", Toast.LENGTH_SHORT).show()
swipeRefreshLayout.isRefreshing = false
}
// OnClickListener to allow navigating from this fragment to the settings one
private val onSettingsButtonClicked: View.OnClickListener = View.OnClickListener {
(activity as MainActivity).openSettingsPage()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = inflater.inflate(R.layout.main_fragment, container, false)
// View initializations
.....
hourlyChart = view.findViewById(R.id.lc_hourly_forecasts)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpChart()
lifecycleScope.launch {
// Shows a lottie animation while the data is being loaded
//scrollView.visibility = View.GONE
//lottieAnimView.visibility = View.VISIBLE
bindUIAsync().await()
// Stops the animation and reveals the layout with the data loaded
//scrollView.visibility = View.VISIBLE
//lottieAnimView.visibility = View.GONE
}
}
#SuppressLint("SimpleDateFormat")
private fun bindUIAsync() = lifecycleScope.async(Dispatchers.Main) {
// fetch current weather
val currentWeather = viewModel.currentWeatherData
// Observe the current weather live data
currentWeather.observe(viewLifecycleOwner, Observer { currentlyLiveData ->
if (currentlyLiveData == null) return#Observer
currentlyLiveData.observe(viewLifecycleOwner, Observer { currently ->
setCurrentWeatherDate(currently.time.toDouble())
// Get the unit system pref's value
val unitSystem = viewModel.preferences.getString(
UNIT_SYSTEM_KEY,
UnitSystem.SI.name.toLowerCase(Locale.ROOT)
)
// set up views dependent on the Unit System pref's value
when (unitSystem) {
UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> {
setCurrentWeatherTemp(currently.temperature)
setUnitSystemImgView(unitSystem)
}
UnitSystem.US.name.toLowerCase(Locale.ROOT) -> {
setCurrentWeatherTemp(
weatherUnitConverter.convertToFahrenheit(
currently.temperature
)
)
setUnitSystemImgView(unitSystem)
}
}
setCurrentWeatherSummaryText(currently.summary)
setCurrentWeatherSummaryIcon(currently.icon)
setCurrentWeatherPrecipProb(currently.precipProbability)
})
})
// fetch the location
val weatherLocation = viewModel.weatherLocation
// Observe the location for changes
weatherLocation.observe(viewLifecycleOwner, Observer { locationLiveData ->
if (locationLiveData == null) return#Observer
locationLiveData.observe(viewLifecycleOwner, Observer { location ->
Log.d(TAG,"location update = $location")
locationTxtView.text = location.name
})
})
// fetch hourly weather
val hourlyWeather = viewModel.hourlyWeatherEntries
// Observe the hourly weather live data
hourlyWeather.observe(viewLifecycleOwner, Observer { hourlyLiveData ->
if (hourlyLiveData == null) return#Observer
hourlyLiveData.observe(viewLifecycleOwner, Observer { hourly ->
val xAxisLabels = arrayListOf<String>()
val sdf = SimpleDateFormat("HH")
for (i in hourly.indices) {
val formattedLabel = sdf.format(Date(hourly[i].time * 1000))
xAxisLabels.add(formattedLabel)
}
setChartAxisLabels(xAxisLabels)
})
})
// fetch weekly weather
val weeklyWeather = viewModel.weeklyWeatherEntries
// get the timezone from the prefs
val tmz = viewModel.preferences.getString(LOCATION_TIMEZONE_KEY, "America/Los_Angeles")!!
// observe the weekly weather live data
weeklyWeather.observe(viewLifecycleOwner, Observer { weeklyLiveData ->
if (weeklyLiveData == null) return#Observer
weeklyLiveData.observe(viewLifecycleOwner, Observer { weatherEntries ->
// update the recyclerView with the new data
(weeklyForecastRCV.adapter as WeeklyWeatherAdapter).updateWeeklyWeatherData(
weatherEntries, tmz
)
for (day in weatherEntries) { //TODO:sp replace this with the full list once the repo issue is fixed
val zdtNow = Instant.now().atZone(ZoneId.of(tmz))
val dayZdt = Instant.ofEpochSecond(day.time).atZone(ZoneId.of(tmz))
val formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
val formattedNowZtd = zdtNow.format(formatter)
val formattedDayZtd = dayZdt.format(formatter)
if (formattedNowZtd == formattedDayZtd) { // find the right week day whose data we want to use for the UI
initTodayData(day, tmz)
}
}
})
})
// get the hourly chart's computed data
val hourlyChartLineData = viewModel.hourlyChartData
// Observe the chart's data
hourlyChartLineData.observe(viewLifecycleOwner, Observer { lineData ->
if(lineData == null) return#Observer
hourlyChart.data = lineData // Error due to the live data value being of type Unit
})
return#async true
}
...
private fun setChartAxisLabels(labels: ArrayList<String>) {
// Populate the X axis with the hour labels
hourlyChart.xAxis.valueFormatter = IndexAxisValueFormatter(labels)
}
/**
* Sets up the chart with the appropriate
* customizations.
*/
private fun setUpChart() {
hourlyChart.apply {
description.isEnabled = false
setNoDataText("Data is loading...")
// enable touch gestures
setTouchEnabled(true)
dragDecelerationFrictionCoef = 0.9f
// enable dragging
isDragEnabled = true
isHighlightPerDragEnabled = true
setDrawGridBackground(false)
axisRight.setDrawLabels(false)
axisLeft.setDrawLabels(false)
axisLeft.setDrawGridLines(false)
xAxis.setDrawGridLines(false)
xAxis.isEnabled = true
// disable zoom functionality
setScaleEnabled(false)
setPinchZoom(false)
isDoubleTapToZoomEnabled = false
// disable the chart's legend
legend.isEnabled = false
// append extra offsets to the chart's auto-calculated ones
setExtraOffsets(0f, 0f, 0f, 10f)
data = LineData()
data.isHighlightEnabled = false
setVisibleXRangeMaximum(6f)
setBackgroundColor(resources.getColor(R.color.bright_White, null))
}
// X Axis setup
hourlyChart.xAxis.apply {
position = XAxis.XAxisPosition.BOTTOM
textSize = 14f
setDrawLabels(true)
setDrawAxisLine(false)
granularity = 1f // one hour
spaceMax = 0.2f // add padding start
spaceMin = 0.2f // add padding end
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
typeface = resources.getFont(R.font.work_sans)
}
textColor = resources.getColor(R.color.black, null)
}
// Left Y axis setup
hourlyChart.axisLeft.apply {
setDrawLabels(false)
setDrawGridLines(false)
setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
isEnabled = false
isGranularityEnabled = true
// temperature values range (higher than probable temps in order to scale down the chart)
axisMinimum = 0f
axisMaximum = when (getUnitSystemValue()) {
UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> 50f
UnitSystem.US.name.toLowerCase(Locale.ROOT) -> 150f
else -> 50f
}
}
// Right Y axis setup
hourlyChart.axisRight.apply {
setDrawGridLines(false)
isEnabled = false
}
}
}
ViewModel class:
class WeatherViewModel(
private val forecastRepository: ForecastRepository,
private val weatherUnitConverter: WeatherUnitConverter,
context: Context
) : ViewModel() {
private val appContext = context.applicationContext
// Retrieve the sharedPrefs
val preferences:SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(appContext)
// This will run only when currentWeatherData is called from the View
val currentWeatherData = liveData {
val task = viewModelScope.async { forecastRepository.getCurrentWeather() }
emit(task.await())
}
val hourlyWeatherEntries = liveData {
val task = viewModelScope.async { forecastRepository.getHourlyWeather() }
emit(task.await())
}
val weeklyWeatherEntries = liveData {
val task = viewModelScope.async {
val currentDateEpoch = LocalDate.now().toEpochDay()
forecastRepository.getWeekDayWeatherList(currentDateEpoch)
}
emit(task.await())
}
val weatherLocation = liveData {
val task = viewModelScope.async(Dispatchers.IO) {
forecastRepository.getWeatherLocation()
}
emit(task.await())
}
val hourlyChartData = liveData {
val task = viewModelScope.async(Dispatchers.Default) {
// Build the chart data
hourlyWeatherEntries.observeForever { hourlyWeatherLiveData ->
if(hourlyWeatherLiveData == null) return#observeForever
hourlyWeatherLiveData.observeForever {hourlyWeather ->
createChartData(hourlyWeather)
}
}
}
emit(task.await())
}
/**
* Creates the line chart's data and returns them.
* #return The line chart's data (x,y) value pairs
*/
private fun createChartData(hourlyWeather: List<HourWeatherEntry>?): LineData {
if(hourlyWeather == null) return LineData()
val unitSystemValue = preferences.getString(UNIT_SYSTEM_KEY, "si")!!
val values = arrayListOf<Entry>()
for (i in hourlyWeather.indices) { // init data points
// format the temperature appropriately based on the unit system selected
val hourTempFormatted = when (unitSystemValue) {
UnitSystem.SI.name.toLowerCase(Locale.ROOT) -> hourlyWeather[i].temperature
UnitSystem.US.name.toLowerCase(Locale.ROOT) -> weatherUnitConverter.convertToFahrenheit(
hourlyWeather[i].temperature
)
else -> hourlyWeather[i].temperature
}
// Create the data point
values.add(
Entry(
i.toFloat(),
hourTempFormatted.toFloat(),
appContext.resources.getDrawable(determineSummaryIcon(hourlyWeather[i].icon), null)
)
)
}
Log.d("MainFragment viewModel", "$values")
// create a data set and customize it
val lineDataSet = LineDataSet(values, "")
val color = appContext.resources.getColor(R.color.black, null)
val offset = MPPointF.getInstance()
offset.y = -35f
lineDataSet.apply {
valueFormatter = YValueFormatter()
setDrawValues(true)
fillDrawable = appContext.resources.getDrawable(R.drawable.gradient_night_chart, null)
setDrawFilled(true)
setDrawIcons(true)
setCircleColor(color)
mode = LineDataSet.Mode.HORIZONTAL_BEZIER
this.color = color // line color
iconsOffset = offset
lineWidth = 3f
valueTextSize = 9f
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
valueTypeface = appContext.resources.getFont(R.font.work_sans_medium)
}
}
// create a LineData object using our LineDataSet
val data = LineData(lineDataSet)
data.apply {
setValueTextColor(R.color.colorPrimary)
setValueTextSize(15f)
}
return data
}
private fun determineSummaryIcon(icon: String): Int {
return when (icon) {
"clear-day" -> R.drawable.ic_sun
"clear-night" -> R.drawable.ic_moon
"rain" -> R.drawable.ic_precipitation
"snow" -> R.drawable.ic_snowflake
"sleet" -> R.drawable.ic_sleet
"wind" -> R.drawable.ic_wind_speed
"fog" -> R.drawable.ic_fog
"cloudy" -> R.drawable.ic_cloud_coverage
"partly-cloudy-day" -> R.drawable.ic_cloudy_day
"partly-cloudy-night" -> R.drawable.ic_cloudy_night
"hail" -> R.drawable.ic_hail
"thunderstorm" -> R.drawable.ic_thunderstorm
"tornado" -> R.drawable.ic_tornado
else -> R.drawable.ic_sun
}
}
}
LazyDeferred:
fun<T> lazyDeferred(block: suspend CoroutineScope.() -> T) : Lazy<Deferred<T>> {
return lazy {
GlobalScope.async {
block.invoke(this)
}
}
}
ScopedFragment :
abstract class ScopedFragment : Fragment(), CoroutineScope {
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
}
override fun onDestroy() {
job.cancel()
super.onDestroy()
}
}
Without the entire environment it's really hard for me to help you debug the whole thing but I am happy to provide you with a couple of things that seem a little bit off at a first glance.
First of all I would avoid managing all CoroutinesScopes and lifecycles by yourself and it's easy to get it wrong. So I would rely on what the Android team has already done. Take a quick look here, it's really easy to setup and use. The dev experience is great.
Posting Deferred on a LiveData and awaiting on the view side looks like a code smell…
What if there's a network error?
It would result in an exception or cancellation exception being thrown.
What if the task was already perform and causes some type of UI consistency problem? These are a couple of edge cases I would not really want to handle.
Just observe a LiveData since it is its main purpose: it's a value holder and it's intended to live throught several lifecycle events in the Fragment. So once view is recreated the value is ready in the LiveData inside the ViewModel.
Your lazyDeferred function is quite smart but in the Android world it's also dangerous. Those coroutines don't live inside any lifecycle-controlled scope so they have a really high chance to end up being leaked. And trust me, you don't want any coroutines being leaked since they continue their work even after viewmodel and fragment destruction which is something you definetely don't want.
All of these are easily fixable by using the dependency I've mentioned before, which I'll paste here once more
Here's a snippet on how you could use those utilities in your ViewModel to ensure the lifecycle of things nor coroutines are causing any issues:
class WeatherViewModel(
private val forecastRepository: ForecastRepository,
context: Context
) : ViewModel() {
private val appContext = context.applicationContext
// Retrieve the sharedPrefs
val preferences:SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(appContext)
// This will run only when currentWeatherData is called from the View
val currentWeatherData = liveData {
val task = viewModelScope.async { forecastRepository.getCurrentWeather() }
emit(task.await())
}
val hourlyWeatherEntries = liveData {
val task = viewModelScope.async { forecastRepository.getHourlyWeather() }
emit(task.await())
}
val weeklyWeatherEntries = liveData {
val task = viewModelScope.async {
val currentDateEpoch = LocalDate.now().toEpochDay()
forecastRepository.getWeekDayWeatherList(currentDateEpoch)
}
emit(task.await())
}
val weatherLocation = liveData {
val task = viewModelScope.async(Dispatchers.IO) {
forecastRepository.getWeatherLocation()
}
emit(task.await())
}
}
By using the following approach all network calls are performed in a parallel fashion and they are all tied to the viewModelScope without writing a single line of handling the CoroutineScope's life. When the ViewModel dies, so will the scope. when the view gets re-created the routines won't execute twice and values will be ready to read.
Regarding the configuration of the chart: I would highly suggest you configure the chart as soon as you have created the view, since it is highly tied together. Configuration is something you want to do just once and may cause visual bugs if some instructions are executed more than once (which I believe it could be happening to you), just saying so because I've had problems with MPAndroid using a Piechart.
More on the chart: All of the logic of constructing the LineData would be better off on a background thread and being exposed through a LiveData in the ViewModel side like you would do with all of the other
val property = liveData {
val deferred = viewModelScope.async(Dispatchers.Default) {
// Heavy building logic like:
createChartData()
}
emit(deferred.await())
}
Pro Kotlin tip: Avoid repeating yourself during those long MPAndroid configurations functions.
Instead of:
view.configureThis()
view.configureThat()
view.enabled = true
Do:
view.apply {
configureThis()
configureThat()
enabled = true
}
I'm sad that I can just give you these hints and being unable to exactly pin-point what your issue is since the bug is heavily related to what is happenning throughout the lifecycle evolution of the runtime but hopefuly this is going to be useful
Answering your comment
If one of your data-streams (LiveData) is dependent on what another data-stream (another LiveData) is going to emit you are looking for LiveData.map and LiveData.switchMap operations.
I imagine that hourlyWeatherEntries is going to be emitting values from time to time.
In that case you can use LiveData.switchMap.
What this does is that everytime the source LiveData emits a value, you're going to get a callback and you are expected to return a new live data with the new value.
You could arrange something like the following:
val hourlyChartData = hourlyWeatherEntries.switchMap { hourlyWeather ->
liveData {
val task = viewModelScope.async(Dispatchers.IO) {
createChartData(hourlyWeather)
}
emit(task.await())
}
}
Using this approach has the benefit that it is completely lazy. That means that NO COMPUTATION is going to take place UNLESS data is being actively observed by some lifecycleOwner. That just means that no callbacks are being triggered unless data is observed in the Fragment
Further explanation on map and switchMap
Since we need to do some asynchronous computation that we don't know when it's going to be done we can't use map. map applies a linear transformation between LiveDatas. Check this out:
val liveDataOfNumbers = liveData { // Returns a LiveData<Int>
viewModelScope.async {
for(i in 0..10) {
emit(i)
delay(1000)
}
}
}
val liveDataOfDoubleNumbers = liveDataOfNumbers.map { number -> number * 2}
This is really useful when the computation is linear and simple. What is happening behind the hood is that the library is handling observing and emitting values for you by means of a MediatorLiveData. What happens here is that whenever liveDataOfNumbers emits a value and liveDataOfDoubleNumbers is being observed the callback gets applied; so the liveDataOfDoubleNumbers is emitting: 0, 2, 4, 6…
The snippet above is equivalent to the following:
val liveDataOfNumbers = liveData { // Returns a LiveData<Int>
viewModelScope.async {
for(i in 0..10) {
emit(i)
delay(1000)
}
}
}
val liveDataOfDoubleNumbers = MediatorLiveData<Int>().apply {
addSource(liveDataOfNumbers) { newNumber ->
// Update MediatorLiveData value when liveDataOfNumbers creates a new number
value = newNumber * 2
}
}
But just using map is much much simpler.
Fantastic!!
Now going to your use-case. Your computation is linear but we want to defer that work to a background coroutine. So we can't exactly tell when something is going to end.
For these use-cases they have created the switchMap operator. What it does it's just the same as map but wraps everything within another LiveData. The intermediate LiveData just acts as a container for the response that is going to come from the coroutine.
So what ends up happening is:
Your coroutine publishes into intermediateLiveData
switchMap does something similar to:
return MediatorLiveData().apply {
// intermediateLiveData is what your callback generates
addSource(intermediateLiveData) { newValue -> this.value = newValue }
} as LiveData
Summing up:
1. Coroutine passes value to intermediateLiveData
2. intermediateLiveData passes value to the hourlyChartData
3. hourlyChartData passes value to the UI
And everything without adding or removing observeForever
Since the liveData {…} is a builder to help us create asynchronous LiveDatas without dealing with the hassle of instantiating them we can use it so our switchMap callback is less verbose.
The function liveData returns a live data of type LiveData<T>. If your repository call already returns a LiveData it's really simple!
val someLiveData = originalLiveData.switchMap { newValue ->
someRepositoryCall(newValue).map { returnedRepoValue -> /*your transformation code here*/}
}
Separate the setupChart and setData logics. Setup chart once out of the observer, inside the observer setData and after that call invalidate().
Try commenting out the invalidate() part and wherever you are calling your search function before it try yourlineChart.clear(); or yourlineChart.clearValues();. This will clear the previous values of the chart and will form chart with new values. So, invalidate() and chart.notifyDataSetChanged() won't not be necessary and it should solve your problem.