Created
May 13, 2018 05:24
-
-
Save adrianhall/bce93231ef094f8edab186022de21dcb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.shellmonger.apps.mynotes.viewmodels | |
import android.arch.lifecycle.LiveData | |
import android.arch.lifecycle.MutableLiveData | |
import android.arch.lifecycle.Transformations | |
import android.arch.lifecycle.ViewModel | |
import android.util.Log | |
import com.shellmonger.apps.mynotes.models.Note | |
import com.shellmonger.apps.mynotes.repositories.MockNotesRepository | |
class NoteDetailViewModel : ViewModel() { | |
companion object { | |
private val TAG = this::class.java.simpleName | |
} | |
private val mutableNoteId: MutableLiveData<String?> = MutableLiveData() | |
private val repository = MockNotesRepository.instance | |
val currentNote: LiveData<Note> | |
init { | |
currentNote = Transformations.switchMap(mutableNoteId, { loadNote(it) }) | |
} | |
private fun loadNote(noteId: String?): LiveData<Note> { | |
Log.d(TAG, "Loading note") | |
val note: Note = if (noteId == null) Note() else repository.getNoteById(noteId) ?: Note() | |
return MutableLiveData<Note>().apply { postValue(note) } | |
} | |
fun setNoteId(noteId: String) { | |
Log.d(TAG, "NoteDetail of $noteId requested") | |
mutableNoteId.postValue(noteId) | |
} | |
fun saveNote(item: Note) { | |
Log.d(TAG, "Saving note ${item.noteId}") | |
repository.saveNote(item) | |
setNoteId(item.noteId) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment