Skip to content

Commit

Permalink
增加Flow流方式
Browse files Browse the repository at this point in the history
  • Loading branch information
aleyn97 committed Nov 22, 2019
1 parent a1cffea commit ce45195
Show file tree
Hide file tree
Showing 9 changed files with 142 additions and 167 deletions.
2 changes: 0 additions & 2 deletions app/src/main/java/com/pcl/mvvm/ui/home/HomeViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.pcl.mvvm.ui.home

import androidx.lifecycle.MutableLiveData
import com.aleyn.mvvm.base.BaseViewModel
import com.pcl.mvvm.data.HomeRepository
import com.pcl.mvvm.network.entity.BannerBean
import com.pcl.mvvm.network.entity.HomeListBean
import com.pcl.mvvm.utils.InjectorUtil
Expand All @@ -26,5 +25,4 @@ class HomeViewModel : BaseViewModel() {
projectData.value = it
})
}

}
14 changes: 5 additions & 9 deletions app/src/main/java/com/pcl/mvvm/ui/project/ProjectFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import com.pcl.mvvm.R
import com.pcl.mvvm.databinding.ProjectFragmentBinding
import com.pcl.mvvm.network.entity.ArticlesBean
import com.pcl.mvvm.ui.detail.DetailActivity
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview

class ProjectFragment : BaseFragment<ProjectViewModel, ProjectFragmentBinding>() {

Expand All @@ -23,16 +25,10 @@ class ProjectFragment : BaseFragment<ProjectViewModel, ProjectFragmentBinding>()
mBinding?.viewModel = viewModel
}

@FlowPreview
@ExperimentalCoroutinesApi
override fun lazyLoadData() {
viewModel.getProjectType()
viewModel.getProjectList(294)
viewModel.defUI.msgEvent.observe(viewLifecycleOwner, Observer {
val msg = it
when (msg.code) {
0 -> {
}
}
})
viewModel.getFirstData()
}

override fun handleEvent(msg: Message) {
Expand Down
47 changes: 38 additions & 9 deletions app/src/main/java/com/pcl/mvvm/ui/project/ProjectViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@ package com.pcl.mvvm.ui.project
import androidx.databinding.ObservableArrayList
import com.aleyn.mvvm.base.BaseViewModel
import com.aleyn.mvvm.event.Message
import com.aleyn.mvvm.network.ExceptionHandle
import com.aleyn.mvvm.network.ResponseThrowable
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.tabs.TabLayout
import com.pcl.mvvm.BR
import com.pcl.mvvm.R
import com.pcl.mvvm.network.entity.ArticlesBean
import com.pcl.mvvm.network.entity.NavTypeBean
import com.pcl.mvvm.utils.InjectorUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import me.tatarka.bindingcollectionadapter2.ItemBinding

/**
Expand All @@ -31,15 +38,37 @@ class ProjectViewModel : BaseViewModel() {

private var page: Int = 0

fun getProjectType() {
launchOnlyresult({
homeRepository.getNaviJson()
}, {
navData.addAll(it)
it.forEach { item ->
navTitle.add(item.name)
}
}, isShowDialog = false)

/**
* 当一个请求结果,依赖另一个请求结果的时候,我们可以用 流的方式如下:
* 以此类推,还可以 用 zip 操作符 对多个请求进行合并,以及 flatMapMerge、flatMapConcat 等。
* 熟悉 RxJava 的你,分分钟钟可以上手的 (斜眼笑 `-` )
*/
@ExperimentalCoroutinesApi
@FlowPreview
fun getFirstData() {
launchUI {
launchFlow { homeRepository.getNaviJson() }
.flatMapConcat {
return@flatMapConcat if (it.isSuccess()) {
navData.addAll(it.data)
it.data.forEach { item -> navTitle.add(item.name) }
launchFlow { homeRepository.getProjectList(page, it.data[0].id) }
} else throw ResponseThrowable(it.errorCode, it.errorMsg)
}
.onStart { defUI.showDialog.postValue(null) }
.flowOn(Dispatchers.IO)
.onCompletion { defUI.dismissDialog.call() }
.catch {
// 错误处理
val err = ExceptionHandle.handleException(it)
LogUtils.d("${err.code}: ${err.errMsg}")
}
.collect {
if (it.isSuccess()) items.addAll(it.data.datas)
}
}

}

fun getProjectList(cid: Int) {
Expand Down
17 changes: 16 additions & 1 deletion mvvmlin/src/main/java/com/aleyn/mvvm/base/BaseViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ import com.aleyn.mvvm.event.Message
import com.aleyn.mvvm.event.SingleLiveEvent
import com.aleyn.mvvm.network.ExceptionHandle
import com.aleyn.mvvm.network.ResponseThrowable
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlin.system.measureTimeMillis

/**
* @auther : Aleyn
Expand All @@ -26,10 +32,19 @@ open class BaseViewModel : AndroidViewModel(Utils.getApp()), LifecycleObserver {
viewModelScope.launch { block() }
}

/**
* 用流的方式进行网络请求
*/
fun <T> launchFlow(block: suspend () -> T): Flow<T> {
return flow {
emit(block())
}
}

/**
* 不过滤请求结果
* @param block 请求体
* @param errorCall 失败回调
* @param error 失败回调
* @param complete 完成回调(无论成功失败都会调用)
* @param isShowDialog 是否显示加载框
*/
Expand Down
22 changes: 7 additions & 15 deletions mvvmlin/src/main/java/com/aleyn/mvvm/event/Message.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,10 @@ package com.aleyn.mvvm.event
* @auther : Aleyn
* time : 2019/11/13
*/
class Message {
var code: Int
var msg: String
var arg1: Int
var arg2: Int
var obj: Any?

constructor(code: Int = 0, msg: String = "", arg1: Int = 0, arg2: Int = 0, obj: Any? = null) {
this.code = code
this.msg = msg
this.arg1 = arg1
this.arg2 = arg2
this.obj = obj
}
}
class Message @JvmOverloads constructor(
var code: Int = 0,
var msg: String = "",
var arg1: Int = 0,
var arg2: Int = 0,
var obj: Any? = null
)
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
package com.aleyn.mvvm.network.interceptor;

/**
* @author ihsan on 21/02/2017.
*/

public enum Level {
/**
* No logs.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,38 +1,25 @@
/*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aleyn.mvvm.network.interceptor


import com.blankj.utilcode.util.JsonUtils
import okhttp3.*
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.Platform.INFO
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
*
* 借鉴其他Demo里的日志打印
* #当日志比较多时,有时候会出现输出不全的情况
*/
class LoggingInterceptor : Interceptor {

var TAG: String = "Logging"
private var tag: String = "HttpLogging"
var isDebug: Boolean = false
var type = Platform.INFO
var requestTag: String = TAG
var responseTag: String = TAG
var type = INFO
var requestTag: String = tag
var responseTag: String = tag
var level = Level.BASIC
val headers = Headers.Builder()
private val headers = Headers.Builder()
var logger: Logger? = null


Expand Down Expand Up @@ -92,7 +79,6 @@ class LoggingInterceptor : Interceptor {
val st = System.nanoTime()
val response = chain.proceed(request)

// val segmentList = (request.tag() as Request).url().encodedPathSegments()
val segmentList = request.url().encodedPathSegments()
val chainMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - st)
val header = response.headers().toString()
Expand All @@ -114,7 +100,7 @@ class LoggingInterceptor : Interceptor {
|| subtype.contains("html"))
) {
val bodyString = responseBody.string()
val bodyJson = Printer.getJsonString(bodyString)
val bodyJson = JsonUtils.formatJson(bodyString)
Printer.printJsonResponse(
this,
chainMs,
Expand All @@ -132,5 +118,5 @@ class LoggingInterceptor : Interceptor {
return response.newBuilder().body(body).build()
}

fun getHeaders(): Headers = headers.build()
private fun getHeaders(): Headers = headers.build()
}
Loading

0 comments on commit ce45195

Please sign in to comment.