Skip to content

Instantly share code, notes, and snippets.

@TORISOUP
Last active August 29, 2015 14:16
Show Gist options
  • Save TORISOUP/83717038ceff78374071 to your computer and use it in GitHub Desktop.
Save TORISOUP/83717038ceff78374071 to your computer and use it in GitHub Desktop.
SuggestText
using System;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
using UnityEngine.UI;
using System.Linq;
using System.Xml.Linq;
namespace UniRxSamples
{
public class SuggestText : MonoBehaviour
{
[SerializeField]
private InputField _inputField;
[SerializeField]
private Text _text;
private readonly string _apiUrlFormat
= "http://www.google.com/complete/search?hl=ja&output=toolbar&q={0}";
private void Start()
{
_inputField
.onValueChange
.AsObservable()
.Throttle(TimeSpan.FromMilliseconds(200))
.SelectMany(word => ObservableWWW.Get(string.Format(_apiUrlFormat, WWW.EscapeURL(word))))
.Select(XMLResultToStrings)
.Where(suggests => suggests.Any())
.Subscribe(suggestResults =>
{
//結果を改行区切りで表示
_text.text = suggestResults.Aggregate((s, n) => s + n + System.Environment.NewLine);
});
}
/// <summary>
/// GoogleSuggestAPIのXMLからSuggest文字列のシーケンスに変換する
/// </summary>
/// <param name="xmlString">対象のXML文字列</param>
/// <returns>Suggest結果の文字列シーケンス</returns>
private IEnumerable<string> XMLResultToStrings(string xmlString)
{
var xml = XDocument.Parse(xmlString);
return xml
.Descendants("CompleteSuggestion")
.Elements(XName.Get("suggestion"))
.Attributes("data")
.Select(x => x.Value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment