Skip to content

Instantly share code, notes, and snippets.

@ShinichiroFunatsu
Last active April 1, 2019 16:08
Show Gist options
  • Save ShinichiroFunatsu/a24a0941ac5540838802eaf0dc6407b0 to your computer and use it in GitHub Desktop.
Save ShinichiroFunatsu/a24a0941ac5540838802eaf0dc6407b0 to your computer and use it in GitHub Desktop.
ViewModel + LiveData + Kotlin Coroutines
class MainActivity : AppCompatActivity() {
val mainViewModel: MainViewModel by lazy {
ViewModelProviders.of(this).get(MainViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainViewModel.getUsr()
mainViewModel.addUser.observe(this, Observer {
when (it) {
is PushResult.Success -> text.text = "OK"
is PushResult.Error -> Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show()
}
})
mainViewModel.updateUser.observe(this, Observer {
when (it) {
is PullResult.Success -> text.text = "OK2"
is PullResult.Error -> Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show()
}
})
}
fun onClick() {
mainViewModel.addUser(mapOf("name" to "Nobita"))
}
}
class MainViewModel(val userRep: UserRepository) : ViewModel() {
val addUser = MutableLiveData<PushResult>()
val updateUser = MutableLiveData<PullResult>()
fun addUser(user: Map<String, Any>) {
viewModelScope.launch(IO) {
addUser.postValue(userRep.push(user))
}
}
fun getUsr() {
viewModelScope.launch(IO) {
updateUser.postValue(userRep.pull())
}
}
}
class UserRepository(val db: FirebaseFirestore) {
// FIXME Map<String, Any> to User class
suspend fun push(user: Map<String, Any>): PushResult {
return suspendCoroutine { continuation ->
db.collection("users")
.add(user)
.addOnCompleteListener {
when (it.isSuccessful) {
true -> continuation.resume(
PushResult.Success(
checkNotNull(it.result)
)
)
false -> continuation.resume(
PushResult.Error(
checkNotNull(it.exception)
)
)
}
}
}
}
suspend fun pull(): PullResult {
return suspendCoroutine { continuation ->
db.collection("users")
.get()
.addOnCompleteListener {
when (it.isSuccessful) {
true -> continuation.resume(
PullResult.Success(
checkNotNull(it.result)
)
)
false -> continuation.resume(
PullResult.Error(
checkNotNull(it.exception)
)
)
}
}
}
}
}
sealed class PushResult {
data class Success(val id: DocumentReference) : PushResult()
data class Error(val e: Throwable) : PushResult()
}
sealed class PullResult {
data class Success(val id: QuerySnapshot) : PullResult()
data class Error(val e: Throwable) : PullResult()
}
@ShinichiroFunatsu
Copy link
Author

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "your.app.pkg"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
    implementation 'androidx.core:core-ktx:1.1.0-alpha05'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha03'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-alpha03'

// async// kotlin coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
    implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'

    // firestore
    implementation 'com.google.firebase:firebase-firestore:18.2.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.2-alpha02'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0-alpha02'
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment