Skip to content

Commit

Permalink
Update worker and some changes
Browse files Browse the repository at this point in the history
  • Loading branch information
hoc081098 committed Oct 31, 2018
1 parent f35d44e commit 65a2790
Show file tree
Hide file tree
Showing 20 changed files with 140 additions and 89 deletions.
4 changes: 2 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
The API key for Google Maps-based APIs is defined as enqueueUpdateCurrentWeatherWorkRequestImmediately string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
You need enqueueUpdateCurrentWeatherWorkRequestImmediately different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
Expand Down
13 changes: 13 additions & 0 deletions app/src/main/java/com/hoc/weatherapp/data/Repository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,19 @@ interface Repository {
* *********************************************************************************************
*/

/**
* Refresh both current weather and five day forecast of [city]
* @return [Single] emit result or error
*/
fun refreshWeatherOf(city: City): Single<Pair<CityAndCurrentWeather, List<DailyWeather>>>

/**
* Refresh current weather of selected city
* @return [Single] emit result or error ([NoSelectedCityException] when have no selected city)
*/
fun refreshCurrentWeatherOfSelectedCity(): Single<CityAndCurrentWeather>


fun getSelectedCityAndCurrentWeatherOfSelectedCity(): Observable<Optional<CityAndCurrentWeather>>

fun getAllCityAndCurrentWeathers(querySearch: String): Observable<List<CityAndCurrentWeather>>
Expand All @@ -48,5 +57,9 @@ interface Repository {

fun getFiveDayForecastOfSelectedCity(): Observable<Optional<List<DailyWeather>>>

/**
* Refresh five day forecast of selected city
* @return [Single] emit result or error ([NoSelectedCityException] when have no selected city)
*/
fun refreshFiveDayForecastOfSelectedCity(): Single<List<DailyWeather>>
}
11 changes: 7 additions & 4 deletions app/src/main/java/com/hoc/weatherapp/data/RepositoryImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,16 @@ class RepositoryImpl(

return cityLocalDataSource
.insertOrUpdateCity(city)
.andThen(currentWeatherLocalDataSource.insertOrUpdateCurrentWeather(weather))
.andThen(
currentWeatherLocalDataSource.insertOrUpdateCurrentWeather(weather)
)
.toSingleDefault(
CityAndCurrentWeather().apply {
this.city = city
this.currentWeather = weather
}
)
.doOnSuccess { debug("saveCityAndCurrentWeather successs", "__WorkerUtil__") }
.doOnSuccess { debug("saveCityAndCurrentWeather success $it", "__WorkerUtil__") }
.subscribeOn(Schedulers.io())
}

Expand All @@ -78,7 +80,7 @@ class RepositoryImpl(
.subscribeOn(Schedulers.io())
.flatMap {
when (it) {
is None -> throw NoSelectedCityException
is None -> Single.error(NoSelectedCityException)
is Some -> weatherApiService
.getCurrentWeatherByCityId(it.value.id)
.subscribeOn(Schedulers.io())
Expand All @@ -90,6 +92,7 @@ class RepositoryImpl(
override fun getSelectedCityAndCurrentWeatherOfSelectedCity(): Observable<Optional<CityAndCurrentWeather>> {
return sharedPrefUtil
.selectedCityObservable
.distinctUntilChanged()
.switchMap { optional ->
when (optional) {
is Some -> currentWeatherLocalDataSource
Expand Down Expand Up @@ -158,7 +161,7 @@ class RepositoryImpl(
.subscribeOn(Schedulers.io())
.flatMap {
when (it) {
is None -> throw NoSelectedCityException
is None -> Single.error(NoSelectedCityException)
is Some -> weatherApiService
.get5DayEvery3HourForecastByCityId(it.value.id)
.subscribeOn(Schedulers.io())
Expand Down
26 changes: 10 additions & 16 deletions app/src/main/java/com/hoc/weatherapp/data/local/CityDao.kt
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
package com.hoc.weatherapp.data.local

import android.database.sqlite.SQLiteConstraintException
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy.FAIL
import androidx.room.Transaction
import androidx.room.Update
import androidx.room.*
import androidx.room.OnConflictStrategy.IGNORE
import com.hoc.weatherapp.data.models.entity.City
import com.hoc.weatherapp.utils.debug

@Dao
abstract class CityDao {
@Insert(onConflict = FAIL)
abstract fun insertCity(city: City)
@Insert(onConflict = IGNORE)
abstract fun insertCity(city: City): Long

@Update
abstract fun updateCity(city: City)
Expand All @@ -23,12 +18,11 @@ abstract class CityDao {

@Transaction
open fun upsert(city: City) {
try {
debug("Insert city=$city", "@@@")
insertCity(city)
} catch (e: SQLiteConstraintException) {
debug("Insert fail --> update city=$city", "@@@")
updateCity(city)
}
insertCity(city)
.takeIf {
debug("insertCity => $it", "__DAO__")
it == -1L
}
?.let { updateCity(city) }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ package com.hoc.weatherapp.data.local
import com.hoc.weatherapp.data.models.entity.City
import io.reactivex.Completable

/**
* A wrapper of [CityDao]
*/

class CityLocalDataSource(private val cityDao: CityDao) {
fun deleteCity(city: City): Completable {
return Completable.fromAction {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
package com.hoc.weatherapp.data.local

import android.database.sqlite.SQLiteConstraintException
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import androidx.room.*
import com.hoc.weatherapp.data.models.entity.CityAndCurrentWeather
import com.hoc.weatherapp.data.models.entity.CurrentWeather
import com.hoc.weatherapp.utils.debug
import io.reactivex.Observable

@Dao
Expand All @@ -29,18 +24,19 @@ abstract class CurrentWeatherDao {
)
abstract fun getAllCityAndCurrentWeathers(querySearch: String): Observable<List<CityAndCurrentWeather>>

@Insert(onConflict = OnConflictStrategy.FAIL)
abstract fun insertCurrentWeather(currentWeather: CurrentWeather)
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insertCurrentWeather(currentWeather: CurrentWeather): Long

@Update
abstract fun updateCurrentWeather(currentWeather: CurrentWeather)

@Transaction
open fun upsert(currentWeather: CurrentWeather) {
try {
insertCurrentWeather(currentWeather)
} catch (e: SQLiteConstraintException) {
updateCurrentWeather(currentWeather)
}
open fun upsert(weather: CurrentWeather) {
insertCurrentWeather(weather)
.takeIf {
debug("insertCurrentWeather => $it", "__DAO__")
it == -1L
}
?.let { updateCurrentWeather(weather) }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,21 @@ import com.hoc.weatherapp.data.models.entity.CurrentWeather
import io.reactivex.Completable
import io.reactivex.Observable

/**
* A wrapper of [CurrentWeatherDao]
*/

class CurrentWeatherLocalDataSource(private val currentWeatherDao: CurrentWeatherDao) {
fun getCityAndCurrentWeatherByCityId(cityId: Long): Observable<CityAndCurrentWeather> {
return currentWeatherDao.getCityAndCurrentWeatherByCityId(cityId)
return currentWeatherDao
.getCityAndCurrentWeatherByCityId(cityId)
.distinctUntilChanged()
}

fun getAllCityAndCurrentWeathers(querySearch: String): Observable<List<CityAndCurrentWeather>> {
return currentWeatherDao.getAllCityAndCurrentWeathers(querySearch)
return currentWeatherDao
.getAllCityAndCurrentWeathers(querySearch)
.distinctUntilChanged()
}

fun insertOrUpdateCurrentWeather(weather: CurrentWeather): Completable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize

/**
* Declaring the column info allows for the renaming of variables without implementing a
* Declaring the column info allows for the renaming of variables without implementing enqueueUpdateCurrentWeatherWorkRequestImmediately
* database migration, as the column name would not change.
*/

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.hoc.weatherapp.data.models.entity
import androidx.room.Embedded

/**
* This class captures the relationship between a [City] and a city's [CurrentWeather]s, which is
* This class captures the relationship between enqueueUpdateCurrentWeatherWorkRequestImmediately [City] and enqueueUpdateCurrentWeatherWorkRequestImmediately city's [CurrentWeather]s, which is
* used by Room to fetch the related entities.
*/

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import kotlinx.android.parcel.Parcelize
import java.util.Date

/**
* Declaring the column info allows for the renaming of variables without implementing a
* Declaring the column info allows for the renaming of variables without implementing enqueueUpdateCurrentWeatherWorkRequestImmediately
* database migration, as the column name would not change.
*/

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class AddCityActivity : MviActivity<AddCityContract.View, AddCityPresenter>(),
setSupportActionBar(toolbar)
supportActionBar?.run {
setDisplayHomeAsUpEnabled(true)
title = "Add a city"
title = "Add enqueueUpdateCurrentWeatherWorkRequestImmediately city"
}

setupAutoCompletePlace()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,17 @@ class CurrentWeatherPresenter(
}

private fun cityAndWeatherPartialChange(): Observable<PartialStateChange> {
val cityAndWeather = repository.getSelectedCityAndCurrentWeatherOfSelectedCity()
.publish { shared ->
Observable.mergeArray(
shared.ofType<None>().switchMap { showError(NoSelectedCityException) },
shared.ofType<Some<CityAndCurrentWeather>>()
.map { it.value }
.map { it.currentWeather }
.map { PartialStateChange.Weather(weather = it) }
return repository.getSelectedCityAndCurrentWeatherOfSelectedCity()
.switchMap { optional ->
when (optional) {
is None -> showError(NoSelectedCityException)
is Some -> PartialStateChange.Weather(weather = optional.value.currentWeather)
.let { Observable.just(it) }
.cast<PartialStateChange>()
.onErrorResumeNext(::showError)
)
}
}
.doOnNext { debug("cityAndWeather $it", TAG) }
return cityAndWeather
}

private fun refreshWeatherPartialChange(): Observable<PartialStateChange> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ class SettingsActivity : AppCompatActivity() {
.skip(1)
.switchMap { showNotification ->
if (showNotification) {
repository.getSelectedCityAndCurrentWeatherOfSelectedCity()
repository
.getSelectedCityAndCurrentWeatherOfSelectedCity()
.observeOn(AndroidSchedulers.mainThread())
.map {
when (it) {
Expand All @@ -79,7 +80,7 @@ class SettingsActivity : AppCompatActivity() {
if (showNotification) {
when (optional) {
is None -> {
view?.snackBar("Please select a city!!")
view?.snackBar("Please select enqueueUpdateCurrentWeatherWorkRequestImmediately city!!")
context.cancelNotificationById(WEATHER_NOTIFICATION_ID)
}
is Some -> optional.value.run {
Expand Down Expand Up @@ -111,7 +112,8 @@ class SettingsActivity : AppCompatActivity() {
sharedPrefUtil.showNotification = newValue
}
key == getString(R.string.key_temperature_unit) && newValue is String -> {
sharedPrefUtil.temperatureUnit = TemperatureUnit.fromString(newValue)
sharedPrefUtil.temperatureUnit =
TemperatureUnit.fromString(newValue) //TODO: change temperature unit on notification
}
key == getString(R.string.key_pressure_unit) && newValue is String -> {
sharedPrefUtil.pressureUnit = PressureUnit.valueOf(newValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ object BlurImageUtil {
Bitmap.Config.ARGB_8888
)

// Create a RenderScript context.
// Create enqueueUpdateCurrentWeatherWorkRequestImmediately RenderScript context.
rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.NORMAL)

// Creates a RenderScript allocation for the blurred result.
// Creates enqueueUpdateCurrentWeatherWorkRequestImmediately RenderScript allocation for the blurred result.
val inAlloc = Allocation.createFromBitmap(rsContext, bitmap)
val outAlloc = Allocation.createTyped(rsContext, inAlloc.type)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.hoc.weatherapp.work

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters

class InitialDelayEnqueueWorker(context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
override fun doWork(): Result {
return when (inputData.getString("TAG")) {
UpdateDailyWeatherWork.TAG -> Result.SUCCESS.also { WorkerUtil.enqueueUpdateCurrentWeatherWorkRequestImmediately() }
UpdateCurrentWeatherWorker.TAG -> Result.SUCCESS.also { WorkerUtil.enqueueUpdateDailyWeatherWorkRequestImmediately() }
else -> Result.FAILURE
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,6 @@ class UpdateCurrentWeatherWorker(context: Context, workerParams: WorkerParameter

companion object {
const val UNIQUE_WORK_NAME = "UpdateCurrentWeatherWorker"
const val TAG = "UpdateCurrentWeatherWorker"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@ class UpdateDailyWeatherWork(context: Context, workerParams: WorkerParameters) :

companion object {
const val UNIQUE_WORK_NAME = "UpdateDailyWeatherWork"
const val TAG = "UpdateDailyWeatherWork"
}
}
Loading

0 comments on commit 65a2790

Please sign in to comment.