应用也简单,EditText中输入内容搜索,然后显示相关内容
先看下布局
RetrofiClient客户端
package com.dongnaoedu.flowpractice.net
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private val instance: Retrofit by lazy {
Retrofit.Builder()
.client(OkHttpClient.Builder().build())
.baseUrl("http://192.168.1.4:8080/kotlinstudyserver/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val articleApi: ArticleApi by lazy {
instance.create(ArticleApi::class.java)
}
}
APIService
package com.dongnaoedu.flowpractice.net
import com.dongnaoedu.flowpractice.model.Article
import retrofit2.http.GET
import retrofit2.http.Query
interface ArticleApi {
//挂起函数
@GET("article")
suspend fun searchArticles(
@Query("key") key: String
): List
}
ViewModel
package com.dongnaoedu.flowpractice.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.dongnaoedu.flowpractice.model.Article
import com.dongnaoedu.flowpractice.net.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
class ArticleViewModel(app: Application) : AndroidViewModel(app) {
//防止flow嵌套flow
val articles = MutableLiveData()
//参数是关键字,就是EditText中输入的字
fun searchArticles(key: String) {
//必须在协程里面使用
viewModelScope.launch {
flow {
val list = RetrofitClient.articleApi.searchArticles(key)
emit(list)
}.flowOn(Dispatchers.IO)
.catch { e -> e.printStackTrace() }
.collect {
articles.setValue(it)
}
}
}
}
fragment界面
package com.dongnaoedu.flowpractice.fragment
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.dongnaoedu.flowpractice.R
import com.dongnaoedu.flowpractice.adapter.ArticleAdapter
import com.dongnaoedu.flowpractice.databinding.FragmentArticleBinding
import com.dongnaoedu.flowpractice.databinding.FragmentUserBinding
import com.dongnaoedu.flowpractice.viewmodel.ArticleViewModel
import com.dongnaoedu.flowpractice.viewmodel.UserViewModel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collect
class ArticleFragment : Fragment() {
private val viewModel by viewModels()
private val mBinding: FragmentArticleBinding by lazy {
FragmentArticleBinding.inflate(layoutInflater)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return mBinding.root
}
//获取关键字,TextView增加一个扩展函数。
//callbackFlow会返回一个Flow
private fun TextView.textWatcherFlow(): Flow = callbackFlow {
val textWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
//往flow里面添加元素
offer(s.toString())
}
}
addTextChangedListener(textWatcher)
//flow关闭的时候移除监听
awaitClose { removeTextChangedListener(textWatcher) }
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
lifecycleScope.launchWhenCreated {
mBinding.etSearch.textWatcherFlow().collect {
Log.d("ning", "collect keywords: $it")
//viewModel请求网络
viewModel.searchArticles(it)
}
}
context?.let {
val adapter = ArticleAdapter(it)
mBinding.recyclerView.adapter = adapter
//viewLifecycleOwner就是Fragment
viewModel.articles.observe(viewLifecycleOwner, { articles ->
adapter.setData(articles)
})
}
}
}
看下 Adapter
package com.dongnaoedu.flowpractice.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.dongnaoedu.flowpractice.databinding.ItemUserBinding import com.dongnaoedu.flowpractice.db.User import com.dongnaoedu.flowpractice.model.Article class ArticleAdapter(private val context: Context) : RecyclerView.Adapter() { private val data = ArrayList() fun setData(data: List) { this.data.clear() this.data.addAll(data) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder { val binding = ItemUserBinding.inflate(LayoutInflater.from(context), parent, false) return BindingViewHolder(binding) } override fun onBindViewHolder(holder: BindingViewHolder, position: Int) { val item = data[position] val binding = holder.binding as ItemUserBinding binding.text.text = item.text } override fun getItemCount() = data.size }
package com.dongnaoedu.flowpractice.adapter
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
class BindingViewHolder(val binding: ViewBinding) : RecyclerView.ViewHolder(binding.root) {
}
itme 布局



