{ super.onStart() myLocationListener.start() // manage other components that need to respond // to the activity lifecycle } public override fun onStop() { super.onStop() myLocationListener.stop() // manage other components that need to respond // to the activity lifecycle } }
private val callback: (Location) -> Unit) { private var enabled = false @OnLifecycleEvent(Lifecycle.Event.ON_START) fun start() { if (enabled) { // connect } } fun enable() { enabled = true if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) { // connect if not connected } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun stop() { // disconnect if connected } }
private val callback: (Location) -> Unit) { private var enabled = false @OnLifecycleEvent(Lifecycle.Event.ON_START) fun start() { if (enabled) { // connect } } fun enable() { enabled = true if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) { // connect if not connected } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun stop() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Get the ViewModel. mModel = ViewModelProviders.of(this).get(NameViewModel::class.java) // Create the observer which updates the UI. val nameObserver = Observer<String> { newName -> // Update the UI, in this case, a TextView. mNameTextView.text = newName } // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer. mModel.currentName.observe(this, nameObserver) } }
// Cria um ViewModel da primeira vez que o método onCreate() // da Activity for chamado. Activities recriadas recebem // a mesma instância de MyViewModel criada pela primeira Activity. val model = ViewModelProviders.of(this).get(MyViewModel::class.java) model.getUsers().observe(this, Observer<List<User>>{ users -> // atualiza a UI }) } }
fornece uma camada de abstração sobre o SQLite, permitindo o acesso de dados robusto, ao mesmo tempo em que permite utilizar todo o poder do banco de dados SQLite
List<User> @Query("SELECT * FROM user WHERE uid IN (:userIds)") fun loadAllByIds(userIds: IntArray): List<User> @Query("SELECT * FROM user WHERE first_name LIKE :first AND " + "last_name LIKE :last LIMIT 1") fun findByName(first: String, last: String): User ... }
RoomDatabase() { abstract fun userDao(): UserDao } val db = Room.databaseBuilder( applicationContext, AppDatabase::class.java, "database-name" ).build()
= ConcertBoundaryCallback(query, myService, myCache) // Use a LiveData object to communicate your network's state back // to your app's UI, as in the following example. Note that error // handling isn't shown in this snippet. // val loadingState: LiveData<MyNetworkState> = // boundaryCallback.loadingState } }
private val cache: MyLocalCache ) : PagedList.BoundaryCallback<Concert>() { // Requests initial data from the network, replacing all content currently // in the database. override fun onZeroItemsLoaded() { requestAndReplaceInitialData(query) } // Requests additional data from the network, appending the results to the // end of the database's existing data. override fun onItemAtEndLoaded(itemAtEnd: Concert) { requestAndAppendData(query, itemAtEnd.key) }
Room to use a PositionalDataSource // object, with position-based loading under the hood. @Query("SELECT * FROM concerts ORDER BY date DESC") fun concertsByDate(): DataSource.Factory<Int, Concert> }
Int) { val concert = getItem(position) if (concert != null) { holder.bindTo(concert) } else { // Null defines a placeholder item - PagedListAdapter automatically // invalidates this row when the actual object is loaded from the // database. holder.clear() } } ... }
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Concert>() { // Concert details may have changed if reloaded from the database, // but ID is fixed. override fun areItemsTheSame(oldConcert: Concert, newConcert: Concert): Boolean = oldConcert.id == newConcert.id override fun areContentsTheSame(oldConcert: Concert, newConcert: Concert): Boolean = oldConcert == newConcert } }
de tarefas assíncronas e condicionar a execução delas. Você pode criar uma task e decidir se ela deve ser executada imediatamente ou após determinado período ou condição.
.setInputData(mapOf("value" to "key").toWorkData()) .build() WorkManager.getInstance().enqueue(firstWork) // Dentro do método doWork() inputData.getString("key", "Default Value")
- não é necessário requisitar - é executado numa thread em background - não deve iniciar nenhuma nova thread - deve retornar um status - não pode rodar pra sempre - ~10 minutos