Android Jetpack

ROOM + FLOW CRUD - 2

----___<<<<< 2022. 7. 11. 09:01

 

FLOW를 이용해서 ROOM을 해보겠습니다.

 

// livedata
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.5.0")

// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$roomVersion")

 

class MainViewModel(application: Application) : AndroidViewModel(application) {

    var readAllData : LiveData<List<TextEntity>>

    val context = getApplication<Application>().applicationContext
    val db = TextDatabase.getDatabase(context)

    init {
        readAllData = db.textDao().getAllData().asLiveData()
    }

    
}

 

class MainActivity : AppCompatActivity() {

    lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        val db = TextDatabase.getDatabase(this)

        val inputArea = findViewById<EditText>(R.id.textInputArea)
        val insertBtn = findViewById<Button>(R.id.insert)
        val getAllBtn = findViewById<Button>(R.id.getData)
        val deleteBtn = findViewById<Button>(R.id.delete)

        insertBtn.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                db.textDao().insert(TextEntity(0, inputArea.text.toString()))
                inputArea.setText("")
            }
        }

        viewModel.readAllData.observe(this, Observer {
            Log.d("MainActivity", it.toString())
        })

//        getAllBtn.setOnClickListener {
//            CoroutineScope(Dispatchers.IO).launch {
//                Log.d("MAINACTIVITY", db.textDao().getAllData().toString())
//            }
//        }

        deleteBtn.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                db.textDao().deleteAllData()
            }
        }

    }
}

 

 

@Dao
interface TextDao {

    @Query("SELECT * FROM text_table")
    fun getAllData() : Flow<List<TextEntity>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(text : TextEntity)

    @Query("DELETE FROM text_table")
    fun deleteAllData()

}

'Android Jetpack' 카테고리의 다른 글

ROOM + FLOW CRUD - 4 (DELTE, UPDATE)  (0) 2022.07.17
ROOM + FLOW CRUD - 3  (0) 2022.07.12
ROOM + FLOW CRUD - 1  (0) 2022.07.03
ROOM + FLOW  (0) 2022.06.27
Coroutine flow  (0) 2022.06.19