Skip to content

Instantly share code, notes, and snippets.

View PatilShreyas's full-sized avatar
👨‍💻
Might be writing code at the moment

Shreyas Patil PatilShreyas

👨‍💻
Might be writing code at the moment
View GitHub Profile
fun getAllPosts() = flow<State<List<Post>>> {
// Emit loading state
emit(State.loading())
val snapshot = mPostsCollection.get().await()
val posts = snapshot.toObjects(Post::class.java)
// Emit success state with data
emit(State.success(posts))
private suspend fun addPost(post: Post) {
viewModel.addPost(post).collect { state ->
when (state) {
is State.Loading -> {
showToast("Loading")
binding.buttonAdd.isEnabled = false
}
is State.Success -> {
showToast("Posted")
private suspend fun loadPosts() {
viewModel.getAllPosts().collect { state ->
when (state) {
is State.Loading -> {
showToast("Loading")
}
is State.Success -> {
val postText = state.data.joinToString("\n") {
"${it.postContent} ~ ${it.postAuthor}"
class MainViewModel(private val repository: PostsRepository) : ViewModel() {
fun getAllPosts() = repository.getAllPosts()
fun addPost(post: Post) = repository.addPost(post)
}
fun addPost(post: Post) = flow<State<DocumentReference>> {
// Emit loading state
emit(State.loading())
val postRef = mPostsCollection.add(post).await()
// Emit success state with post reference
emit(State.success(postRef))
sealed class State<T> {
class Loading<T> : State<T>()
data class Success<T>(val data: T) : State<T>()
data class Failed<T>(val message: String) : State<T>()
companion object {
fun <T> loading() = Loading<T>()
fun <T> success(data: T) = Success(data)
fun <T> failed(message: String) = Failed<T>(message)
}
data class Post(
val postContent: String? = null,
val postAuthor: String? = null
)
dependencies {
// Kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// Kotlin Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.5"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.5'
public class Main {
public static void main(String[] args) {
Life life = DaggerLifeComponent.create().getLife();
life.enjoy();
}
}
@Singleton
@Component
public interface LifeComponent {
Life getLife();
}