Updated 1 April 2019
Coroutine:
coroutines are light-weight threads. They are launched with launch coroutine builder in a context of some CoroutineScope. A coroutine is a method that executes for a certain period, suspends, and permits other coroutines to run.
Use Cases:
The common use cases for coroutines on Android would be fetching data from the network, parsing large JSON datasets, writing data to a database. Therefore, calling code like this from the main thread can cause the app to pause, stutter, or even freeze. And if you block the main thread for too long, the app may even crash and present an Application Not Responding dialog.
Add dependenceis:
To get started with coroutines on Android you will need to add coroutine and following dependencies.
1 2 3 4 5 6 7 8 |
//Coroutines implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1' //Live data and life cycles implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0' implementation 'androidx.lifecycle:lifecycle-livedata:2.0.0' |
Database Call using coroutines
We have ViewModel with some LiveData objects that the Activity will be able to observe added. Add a coroutine scope to MainViewModel. In Kotlin, all coroutines run inside a CoroutineScope.A scope controls the lifetime of coroutines through its job.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import androidx.annotation.UiThread import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.webkul.remindme.android.model.ScheduleReminderData import com.webkul.remindme.android.roomdb.DataBaseManager import kotlinx.coroutines.* class MainViewModel : ViewModel() { private val _scheduleReminderData = MutableLiveData<List<ScheduleReminderData>>() @UiThread fun loadScheduleReminderData(): LiveData<List<ScheduleReminderData>> { ioMain({ DataBaseManager .getScheduleReminderData() }) { _scheduleReminderData.value = it } return _scheduleReminderData } fun <T : Any> ioMain( work: suspend (() -> T?), callback: ((T?) -> Unit)? = null ): Job = CoroutineScope(Dispatchers.Main).launch { val data = CoroutineScope(Dispatchers.IO).async { return@async work() }.await() callback?.let { it(data) } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import androidx.annotation.WorkerThread import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.webkul.remindme.android.ReminderApplication import com.webkul.remindme.android.model.ScheduleReminderData import com.webkul.remindme.android.model.ScheduleRemindersData @Database(entities = [ScheduleReminderData::class], version = 1, exportSchema = false) abstract class ScheduleReminderDataDatabase : RoomDatabase() { abstract fun scheduleRemindersData(): ScheduleRemindersData companion object { private var INSTANCE: ScheduleReminderDataDatabase? = null @WorkerThread fun get(): ScheduleReminderDataDatabase { if (INSTANCE == null) { INSTANCE = Room .inMemoryDatabaseBuilder( ReminderApplication.applicationContext(), ScheduleReminderDataDatabase::class.java ) .fallbackToDestructiveMigration() .build() } return INSTANCE!! } } } |
1 2 3 4 5 |
@Dao interface ScheduleRemindersData { @Query("SELECT * FROM ScheduleReminderData") fun getAll(): List<ScheduleReminderData> } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import android.os.Bundle import android.util.Log import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.RecyclerView import com.webkul.remindme.android.BR import com.webkul.remindme.android.R import com.webkul.remindme.android.adapter.RemindersRvdapter import com.webkul.remindme.android.databinding.ActivityMainBinding import com.webkul.remindme.android.handler.MainActivityHandler import com.webkul.remindme.android.model.MainViewModel class MainActivity : BaseActivity() { val mViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mViewModel.loadScheduleReminderData().observe(this, Observer { // use it }) } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.