Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const val FROM_DB = "FROM_DB"
- const val FROM_API = "FROM_API"
- class MainActivity : AppCompatActivity(), CoroutineScope {
- //region Coroutines initialization
- private val job = Job()
- override val coroutineContext: CoroutineContext = Dispatchers.Main + job
- //endregion
- //region variable declaration
- private val todos = ArrayList<Todo>()
- private var adapter: TodoAdapter? = null
- //endregion
- //region livedata variables
- private val progressLiveData = MutableLiveData<Boolean>()
- private val todoListLiveData = MutableLiveData<Result.ResultWrapper<List<Todo>, String>>()
- //endregion
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- initAdapter()
- initRealm()
- setListeners()
- getLocalTodos()
- getRemoteTodos()
- }
- /**
- * Adapter is initialized here. Called once from [onCreate()]
- */
- private fun initAdapter() {
- adapter = TodoAdapter(this, todos)
- rvTodos.layoutManager = LinearLayoutManager(this)
- rvTodos.adapter = adapter
- }
- /**
- * Realm instance is initialized here. Called once from [onCreate()]
- */
- private fun initRealm() {
- Realm.init(this)
- val config = RealmConfiguration
- .Builder()
- .name("simplified_caching.realm")
- .schemaVersion(1)
- .deleteRealmIfMigrationNeeded()
- .build()
- Realm.setDefaultConfiguration(config)
- }
- /**
- * LiveData observers are set here
- * [todoListLiveData] observes for changes to [todo] which is the data source for our [adapter]
- * [progressLiveData] observes a boolean which is responsible for flipping our [vfMain]
- */
- private fun setListeners() {
- progressLiveData.observe(this, Observer { isLoading ->
- vfMain.displayedChild = if(isLoading) 0 else 1
- })
- todoListLiveData.observe(this, Observer { result ->
- val isFromDb = result.message == FROM_DB
- if(!isFromDb) {
- //presist data if changes observered are not from DB
- result.data.saveAll()
- }
- //for any change to [todos] clear list, add new data to list, notifiy adapter
- clearAndAllToList(result.data)
- adapter?.notifyDataSetChanged()
- })
- }
- private fun clearAndAllToList(todosToAdd: List<Todo>?) {
- todos.clear()
- todosToAdd?.let { todos.addAll(it) }
- }
- /**
- * Get cached data from Realm
- */
- private fun getLocalTodos() {
- progressLiveData.value = false
- val todosFromDb = Todo().queryAll()
- todoListLiveData.value = Result.ResultWrapper(todosFromDb, FROM_DB)
- }
- /**
- * Get remote data from API using Retrofit
- */
- private fun getRemoteTodos() {
- launch {
- if(todos.isEmpty()) {
- progressLiveData.value = true
- }
- val todosFromApi = ApiController.retrofit.create<ApiInterface>().getTodos().await()
- progressLiveData.value = false
- todoListLiveData.value = Result.ResultWrapper(todosFromApi, FROM_API)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement