Skip to content
This repository has been archived by the owner on Dec 7, 2019. It is now read-only.

StoreRoom #338

Merged
merged 12 commits into from
May 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ android:
- tools
- platform-tools
- build-tools-27.0.3
- android-25
- android-27
- extra-android-m2repository
licenses:
- 'android-sdk-license-.+'
script:
- ./gradlew check --stacktrace
after_success:
- gradle/deploy_snapshot.sh
before_install:
- yes | sdkmanager "platforms;android-27"
branches:
except:
- gh-pages
Expand Down
28 changes: 23 additions & 5 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.getkeepsafe.dexcount'

apply plugin: 'kotlin-kapt'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

woohoo!

android {
compileSdkVersion versions.compileSdk
buildToolsVersion versions.buildTools
Expand Down Expand Up @@ -31,6 +32,7 @@ android {
exclude 'META-INF/rxjava.properties'
}
}
def room_version = "1.1.0" // or, for latest rc, use "1.1.1-rc1"

dependencies {

Expand All @@ -48,9 +50,25 @@ dependencies {
annotationProcessor libraries.immutablesValue // <-- for annotation processor
compileOnly libraries.immutablesValue // <-- for annotation API
compileOnly libraries.immutablesGson // for annotations
implementation 'com.nytimes.android:store3:3.0.1'
implementation 'com.nytimes.android:cache3:3.0.1'
implementation 'com.nytimes.android:middleware3:3.0.1'
implementation 'com.nytimes.android:filesystem3:3.0.1'
implementation project(':store')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

might need to flip before checking in....

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will do once I can push the new snapshot thanks!

implementation project(':cache')
implementation project(':middleware')
implementation project(':filesystem')
implementation libraries.rxAndroid2
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
kapt "android.arch.persistence.room:compiler:$room_version"

// androidTestImplementation "android.arch.persistence.room:testing:$room_version"
// optional - RxJava support for Room
implementation "android.arch.persistence.room:rxjava2:$room_version"
}
repositories {
mavenCentral()
}

configurations.all {
resolutionStrategy.force 'com.android.support:support-v4:26.1.0'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems we're still using support lib v26.1.0 while there is latest one v27.1.1. Any plan to upgrade?

}
119 changes: 0 additions & 119 deletions app/src/main/java/com/nytimes/android/sample/SampleApp.java

This file was deleted.

133 changes: 133 additions & 0 deletions app/src/main/java/com/nytimes/android/sample/SampleApp.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package com.nytimes.android.sample

import android.app.Application
import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.nytimes.android.external.fs3.SourcePersisterFactory
import com.nytimes.android.external.store3.base.Persister
import com.nytimes.android.external.store3.base.impl.BarCode
import com.nytimes.android.external.store3.base.impl.MemoryPolicy
import com.nytimes.android.external.store3.base.impl.Store
import com.nytimes.android.external.store3.base.impl.StoreBuilder
import com.nytimes.android.external.store3.middleware.GsonParserFactory
import com.nytimes.android.sample.data.model.GsonAdaptersModel
import com.nytimes.android.sample.data.model.RedditData
import com.nytimes.android.sample.data.remote.Api
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okio.BufferedSource
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit

class SampleApp : Application() {

var nonPersistedStore: Store<RedditData, BarCode>? = null
var persistedStore: Store<RedditData, BarCode>? =null
private var persister: Persister<BufferedSource, BarCode>? =null
private val sampleRoomStore=SampleRoomStore(this)

override fun onCreate() {
super.onCreate()
appContext = this
initPersister();
nonPersistedStore = provideRedditStore();
persistedStore=providePersistedRedditStore();
RoomSample()
}

private fun RoomSample() {
var foo = sampleRoomStore.store.get("")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ strings1 -> val success = strings1 != null }) { throwable -> throwable.stackTrace }

foo = Observable.timer(15, TimeUnit.SECONDS)
.subscribe { makeFetchRequest() }
}

private fun makeFetchRequest() {
val bar = sampleRoomStore.store.fetch("")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ strings1 -> val success = strings1 != null }) { throwable -> throwable.stackTrace }
}

private fun initPersister() {
try {
persister = newPersister()
} catch (exception: IOException) {
throw RuntimeException(exception)
}

}

/**
* Provides a Store which only retains RedditData for 10 seconds in memory.
*/
private fun provideRedditStore(): Store<RedditData, BarCode> {
return StoreBuilder.barcode<RedditData>()
.fetcher { barCode -> provideRetrofit().fetchSubreddit(barCode.key, "10") }
.memoryPolicy(
MemoryPolicy
.builder()
.setExpireAfterWrite(10)
.setExpireAfterTimeUnit(TimeUnit.SECONDS)
.build()
)
.open()
}

/**
* Provides a Store which will persist RedditData to the cache, and use Gson to parse the JSON
* that comes back from the network into RedditData.
*/
private fun providePersistedRedditStore(): Store<RedditData, BarCode> {
return StoreBuilder.parsedWithKey<BarCode, BufferedSource, RedditData>()
.fetcher({ this.fetcher(it) })
.persister(newPersister())
.parser(GsonParserFactory.createSourceParser(provideGson(), RedditData::class.java))
.open()
}

/**
* Returns a new Persister with the cache as the root.
*/
@Throws(IOException::class)
private fun newPersister(): Persister<BufferedSource, BarCode> {
return SourcePersisterFactory.create(this.cacheDir)
}

/**
* Returns a "fetcher" which will retrieve new data from the network.
*/
private fun fetcher(barCode: BarCode): Single<BufferedSource> {
return provideRetrofit().fetchSubredditForPersister(barCode.key, "10")
.map({ it.source() })
}

private fun provideRetrofit(): Api {
return Retrofit.Builder()
.baseUrl("http://reddit.com/")
.addConverterFactory(GsonConverterFactory.create(provideGson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.validateEagerly(BuildConfig.DEBUG) // Fail early: check Retrofit configuration at creation time in Debug build.
.build()
.create(Api::class.java)
}

internal fun provideGson(): Gson {
return GsonBuilder()
.registerTypeAdapterFactory(GsonAdaptersModel())
.create()
}

companion object {
var appContext: Context? = null
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not great, lets avoid having objects create a static reference to themselves?

}
}
60 changes: 60 additions & 0 deletions app/src/main/java/com/nytimes/android/sample/SampleRoomStore.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.nytimes.android.sample

import android.arch.persistence.room.Dao
import android.arch.persistence.room.Database
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Insert
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.Query
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.content.Context
import com.nytimes.android.external.store3.base.Fetcher
import com.nytimes.android.external.store3.base.impl.room.StoreRoom
import com.nytimes.android.external.store3.base.room.RoomPersister
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Single

@Entity
data class User(
@PrimaryKey(autoGenerate = true)
var uid: Int = 0,
val name: String)

@Dao
interface UserDao {
@Query("SELECT name FROM user")
fun loadAll(): Flowable<List<String>>

@Insert
fun insertAll(user: User)

}

@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}

class SampleRoomStore(context: Context){
val db = Room.databaseBuilder(context, AppDatabase::class.java, "db").build()

val fetcher = Fetcher<User, String> { Single.just(User(name = "Mike")) }
val persister = object : RoomPersister<User, List<String>, String> {

override fun read(key: String): Observable<List<String>> {
return db.userDao().loadAll().toObservable()
}

override fun write(key: String, user: User) {
db.userDao().insertAll(user)
}
}

val store = StoreRoom.from(fetcher, persister)
}




Loading