Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import org.ninetripods.mq.study.BaseActivity
import org.ninetripods.mq.study.R
import org.ninetripods.mq.study.kotlin.ktx.id
Expand Down Expand Up @@ -72,15 +70,29 @@ class FlowStudyActivity : BaseActivity() {
.catch { exception -> exception.message?.let { log(it) } }
}

mFlowModel.fetchStateFlowData()

//SharedFlow
lifecycleScope.launch {
mFlowModel.mSharedFlow.collect { value ->
log("collect: $value")
mTvShareF.text = value
}
}

//TODO
val testSharedFlow = MutableSharedFlow<String>(extraBufferCapacity = 1)
runBlocking {
CoroutineScope(Job()).launch {
testSharedFlow
.onStart { log("start") }
.collect { log(it) }
}
delay(1000) // to give enough time for println to be executed before execution finishes
}
testSharedFlow.tryEmit("a")
testSharedFlow.tryEmit("b")
runBlocking { delay(100) } // to give enough time for println to be executed before execution finishes

// mFlowModel.fetchStateFlowData()
}

override fun initEvents() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import org.ninetripods.mq.study.kotlin.ktx.log
class FlowViewModel : ViewModel() {
//MutableStateFlow 可读可写
private val _stateFlow = MutableStateFlow(DataState.Success("default"))

//StateFlow 只可读
val mStateFlow: StateFlow<DataState> = _stateFlow

//SharedFlow
private val _sharedFlow = MutableSharedFlow<String>(
replay = 1,//重播给新订阅者的数量
replay = 0,//重播给新订阅者的数量
extraBufferCapacity = 1,//当有剩余缓冲空间时,emit不会挂起
onBufferOverflow = BufferOverflow.DROP_LATEST //配置缓冲区的溢出操作
onBufferOverflow = BufferOverflow.SUSPEND //配置缓冲区的溢出操作
)
val mSharedFlow: SharedFlow<String> = _sharedFlow

Expand All @@ -34,10 +35,13 @@ class FlowViewModel : ViewModel() {
}

fun fetchSharedFlowData() {
log("tryEmit: sharedFlow1")
_sharedFlow.tryEmit("sharedFlow1")
log("tryEmit: sharedFlow2")
_sharedFlow.tryEmit("sharedFlow2")
// viewModelScope.launch {
// delay(5000)
log("tryEmit: sharedFlow1")
_sharedFlow.tryEmit("sharedFlow1")
log("tryEmit: sharedFlow2")
_sharedFlow.tryEmit("sharedFlow2")
//}
}

}