kotlinx.coroutines.flow

How to replace LiveData with Flow

懵懂的女人 提交于 2021-02-08 09:15:36
问题 I've one LiveData named sortOrder and then I've another variable named myData that observes any change to sortOrder and populates data accordingly. class TestViewModel @ViewModelInject constructor() : ViewModel() { private val sortOrder = MutableLiveData<String>() val myData = sortOrder.map { Timber.d("Sort order changed to $it") "Sort order is $it" } init { sortOrder.value = "year" } } Observing in Activity class TestActivity : AppCompatActivity() { private val viewModel: TestViewModel by

How to replace LiveData with Flow

↘锁芯ラ 提交于 2021-02-08 09:13:31
问题 I've one LiveData named sortOrder and then I've another variable named myData that observes any change to sortOrder and populates data accordingly. class TestViewModel @ViewModelInject constructor() : ViewModel() { private val sortOrder = MutableLiveData<String>() val myData = sortOrder.map { Timber.d("Sort order changed to $it") "Sort order is $it" } init { sortOrder.value = "year" } } Observing in Activity class TestActivity : AppCompatActivity() { private val viewModel: TestViewModel by

How to cancel/unsubscribe from coroutines Flow

谁说我不能喝 提交于 2020-05-11 07:50:21
问题 I notice a strange behavior when trying to prematurely cancel from a Flow. Take a look at the following example. This is a simple flow that emits integer values private fun createFlow() = flow { repeat(10000) { emit(it) } } Then I call the createFlow function using this code CoroutineScope(Dispatchers.Main).launch { createFlow().collect { Log.i("Main", "$it isActive $isActive") if (it == 2) { cancel() } } } This is what is printed out 0 isActive true 1 isActive true 2 isActive true 3 isActive

How can I send items to a Kotlin.Flow (like a Behaviorsubject)

爷,独闯天下 提交于 2019-11-29 20:10:29
问题 I wanted to know how can I send/emit items to a Kotlin.Flow , so my use case is: In the consumer/ViewModel/Presenter I can subscribe with the collect function: fun observe() { coroutineScope.launch { // 1. Send event reopsitory.observe().collect { println(it) } } } But the issue is in the Repository side, with RxJava we could use a Behaviorsubject expose it as an Observable/Flowable and emit new items like this: behaviourSubject.onNext(true) But whenever I build a new flow: flow { } I can